Simple Nature - Light and Matter

(Martin Jones) #1
>>> print(time2(1.0,10)) # h, n
0.35864270709233342

But by increasingnto ten thousand, we get an answer that’s as
close as we need, given the limited accuracy of the raw data:

>>> print(time2(1.0,10000)) # h, n
0.44846664060793945

A subtle point is that we changedyin line 9, andthenon line
10 we calculatedv, which depends ony. Sinceyis only changing
by a ten-thousandth of a meter with each step, you might think
this wouldn’t make much of a difference, and you’d be almost right,
except for one small problem: if we swapped lines 9 and 10, then
the very first time through the loop, we’d havev=0, which would
produce a division-by-zero error when we calculateddt! Actually
what would make the most sense would be to calculate the velocity
at heightyand the velocity at heighty+dy(recalling thatdy is
negative), average them together, and use that value ofyto calculate
the best estimate of the velocity between those two points. Since
the acceleration is constant in the present example, this modification
results in a program that gives an exact result even forn=1:

1 import math
2 def time3(h,n):
3 g=9.8
4 y=h
5 v=0
6 dy = -h/n
7 t=0
8 for i in range(n):
9 y_old = y
10 y = y+dy
11 v_old = math.sqrt(2g(h-y_old))
12 v = math.sqrt(2g(h-y))
13 v_avg = -(v_old+v)/2.
14 dt=dy/v_avg
15 t=t+dt
16 return t
17


>>> print(time3(1.0,1)) # h, n
0.45175395145262565

Now we’re ready to attack a problem that challenged the best
minds of Europe back in the days when there were no computers.
In 1696, the mathematician Johann Bernoulli posed the following

Section 2.2 Numerical techniques 93
Free download pdf