Joel DeWitt
Joel DeWitt

Reputation: 1306

Unexpected numerical behavior in JavaScript

Have some JavaScript to model a simple pendulum:

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];
}

When I do dt_read = pendulum.elements.dt_read; from a form and then dt = dt_read.value; to retreive the actual value--that works--but when I now do with time[i + 1] = time[i] + dt; inside I get something unexpected: ["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] at element [34], for example. As an old Fortraner, this is confusing...any insights will be appreciated. Thanks!

Upvotes: 0

Views: 58

Answers (1)

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

dt = dt_read.value will be a string, assuming it's coming from a form element.

Use: dt = parseFloat(dt_read.value)

Upvotes: 5

Related Questions