简体   繁体   中英

Solving Lotka–Volterra equations with math.js

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.

解决方案:删除所有单位,例如“ s”,“ m / s”等。要么如此,要么所有单位必须匹配。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM