#!/usr/bin/perl
#
# a simple numerical simulation of a spring moving in 
#   simple harmonic motion.
#
# MWR 2/5/2005

# pi
$pi = 3.14159;

# spring constant, N/m
$k = 100.0;
# mass attached to spring, kg
$m = 10.0;
# initial displacement from rest, m
$A = 1.0;
# how many timesteps per oscillation?
$num_step = 10000.0;
# how many periods should we simulate?
$num_period = 100;

# angular frequency of oscillation, rad/s
$omega = sqrt($k/$m);
# period of oscillation, s
$period = (2.0*$pi)/$omega;
# timestep
$dt = $period/$num_step;

$start_time = 0;
$end_time = $num_period*$period;

$iter = 0;
for ($t = $start_time; $t <= $end_time; $t += $dt) {

  $pos = $A*cos($omega*$t);
  $vel = 0.0 - ($omega*$A*sin($omega*$t));
  $accel = 0.0 - ($omega*$omega*$A*cos($omega*$t));

  $ke = 0.5*$m*$vel*$vel;
  $spe = 0.5*$k*($pos*$pos);
  $tot_e = $ke + $spe;

  # print out information at this time
  printf " %8d  t %9.4e  pos %9.4e  vel %9.4e  KE %9.4e  SPE %9.4e  tot_e %9.4e \n",
        $iter, $t, $pos, $vel, $ke, $spe, $tot_e;

  $iter++;

}


exit(0);
