有一些JavaScript可以模拟一个简单的摆锤:
function amp() {
"use strict";
var i_max,
m,
g,
f_osc,
theta,
theta_plot,
omega,
omega_plot,
a,
e,
e_plot,
de,
time,
pi,
theta0,
read_ratio,
const0,
T,
result,
omega_read,
dt_read,
dt,
i,
pendulum;
i_max = 500;
m = 1.0;
g = 9.8;
f_osc = 0.0;
theta = [];
theta_plot = [];
omega = [];
omega_plot = [];
a = [];
e = [];
e_plot = [];
de = [];
time = [];
pendulum = document.forms.pendulum;
pi = Math.acos(-1.0);
theta0 = pendulum.elements.theta0;
theta[0] = 0.1;
read_ratio = pendulum.elements.read_ratio;
const0 = 9.0;
T = 2 * pi * Math.sqrt(Math.pow(const0, -1));
result = T.toFixed(2);
document.getElementById('output').innerHTML = result;
omega_read = pendulum.elements.omega_read;
omega[0] = 0.0;
dt_read = pendulum.elements.dt_read;
dt = dt_read.value;
e[0] = 0.5 * (Math.pow(omega[0], 2) + const0 * Math.pow(theta[0], 2));
time[0] = 0.0;
theta_plot[0] = [time[0], theta[0]];
omega_plot[0] = [time[0], omega[0]];
e_plot[0] = [time[0], e[0]];
i = 0;
do {
f_osc = -const0 * Math.sin(theta[i]);
a[i] = f_osc / m;
e[i] = 0.5 * (Math.pow(omega[i], 2) + const0 * Math.pow(theta[i], 2));
de[i] = e[i] - e[0];
theta[i + 1] = theta[i] + omega[i] * dt + 0.5 * a[i] * dt * dt;
f_osc = -const0 * Math.sin(theta[i + 1]);
a[i + 1] = f_osc / m;
omega[i + 1] = omega[i] + 0.5 * (a[i + 1] + a[i]) * dt;
e[i] = 0.5 * (Math.pow(omega[i + 1], 2) + const0 * Math.pow(theta[i + 1], 2));
de[i] = e[i] - e[0];
time[i + 1] = time[i] + dt;
theta_plot[i + 1] = [time[i + 1], theta[i + 1]];//match indices with Fortran
omega_plot[i + 1] = [time[i + 1], omega[i + 1]];
e_plot[i + 1] = [time[i + 1], e[i].toFixed(5)];
i = i + 1;
} while (i < i_max);
console.log(theta_plot[34]);
return [theta_plot, omega_plot, e_plot];
}
当我从表单中执行
dt_read = pendulum.elements.dt_read;
然后再执行dt = dt_read.value;
求出实际值时-可行-但是当我现在将do
放入内部time[i + 1] = time[i] + dt;
的时候,我得到了意外的消息:["00.010.010.010.010.010.010.010.010.010.010.010.010…10.010.010.010.010.010.010.010.010.010.010.010.01", 0.05239558023305029]
元素[34]
, 例如。作为旧的Fortraner,这令人困惑...任何见解都会受到赞赏。谢谢! 最佳答案
dt = dt_read.value
将是一个字符串,假设它来自表单元素。
使用:dt = parseFloat(dt_read.value)
关于javascript - JavaScript中的意外数值行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24807324/