有一些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,这是令人困惑的...任何见解将不胜感激。谢谢!
答案 0 :(得分:5)
dt = dt_read.value
将是一个字符串,假设它来自表单元素。
使用:dt = parseFloat(dt_read.value)