2
votes

There's one example on solving differential equations in math.js on the math.js homepage, but it's fairly complex and does not provide enough information for me personally to be able to apply math.js for other similar problems. So, what I'm trying to do is solving the Lotka–Volterra equations for predator-prey simulation. There are two equations in the system:

dx/dt = ax - bxy

dy/dt = cxy - y

Enconding this in math.js, I got

math.import({ndsolve:ndsolve});
const sim2 = math.parser();
sim2.eval("dxdt(x, y) = x - x * y");
sim2.eval("dydt(x, y) = x * y - y");
sim2.eval("dt = 1.0 s");                // Simulation timestep
sim2.eval("x0 = 0");
sim2.eval("y0 = 0");
sim2.eval("tfinal = 100 s");          // Simulation duration
sim2.eval("result_stage1 = ndsolve([dxdt, dydt], [x0, y0], dt, tfinal)");

where ndsolve is from the rocket trajectory example: http://mathjs.org/examples/browser/rocket_trajectory_optimization.html.html

function ndsolve(f, x0, dt, tmax) {
    var n = f.size()[0];  // Number of variables
    var x = x0.clone();   // Current values of variables
    var dxdt = [];        // Temporary variable to hold time-derivatives
    var result = [];      // Contains entire solution

    var nsteps = math.divide(tmax, dt);   // Number of time steps
    for(var i=0; i<nsteps; i++) {
        // Compute derivatives
        for(var j=0; j<n; j++) {
            dxdt[j] = f.get([j]).apply(null, x.toArray());
        }
        // Euler method to compute next time step
        for(var j=0; j<n; j++) {
    console.log(x.get([j]));
    console.log(dt);
            x.set([j], math.add(x.get([j]), math.multiply(dxdt[j], dt)));
        }
        result.push(x.clone());
    }

    return math.matrix(result);
}

However, running this code I get the error

Unexpected type of argument in function add (expected: number or Complex or BigNumber or Fraction, actual: Unit, index: 1)

What's the source of this error? Am I missing the correct units?

Grateful for any help.

1
What is the contents of the console log? Could you also log the other operands of the expression? Hypothesis to test/falsify: x.get returns an array if an array is given as argument.Lutz Lehmann
@LutzL Pic of the console log: snag.gy/J3aXUV.jpgOlle Härstedt
I'm getting a suspicion this is a unit problem, since I didn't define any units at all in my implementation.Olle Härstedt
Seemed to "work" if I removed the "s" unit from dt.Olle Härstedt
Yes, usually numeric codes are for unit-less problems. The interpretation of the results, units, scales, shape happens outside these generalist algorithms. It is interesting that "1 s" actually gets parsed as unit.Lutz Lehmann

1 Answers

0
votes

Solution: Remove all units, like 's', 'm/s' etc. Either that, or all units have to match.