在math.js中,在math.js主页上有一个关于求解微分方程的例子,但是它相当复杂,并且没有提供足够的信息让我个人能够将math.js应用于其他类似的问题。所以,我要做的是解决用于捕食-食饵模拟的Lotka-Volterra方程。在这个系统中有两个方程:
dx/dt = ax - bxy
dy/dt = cxy - y在math.js里,我得到了
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)");ndsolve来自火箭轨道的例子: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);
}但是,运行此代码将得到错误信息。
函数添加中意想不到的参数类型(预期:数字或复数或BigNumber或分数,实际:单位,索引: 1)
这个错误的来源是什么?我错过了正确的单位吗?
感谢你的帮助。
发布于 2017-11-22 10:58:34
解决方案:删除所有单位,如's','m/s‘等。要么,或所有单位必须匹配。
https://stackoverflow.com/questions/47372456
复制相似问题