# Python examples (was Re: Some python comments/questions (correction))

Tim Peters (tim@ksr.com)
Wed, 13 Oct 93 17:19:36 -0400

> ... a simple numerical algorithm (printing Fibonacci numbers? who can
> think of a more interesting example?), ...

lots of things interesting to number-crunchers: long ints, short ints,
floats, implicit & explicit coercions, useful builtin functions, multiple
assignment, simple import, painless quick output, & multi-valued
functions:

print 'approximations to pi'

import math
top = 31415926535897932385L
bottom = 10000000000000000000L
p2, p1 = 0, 1
q2, q1 = 1, 0

while q1 < 1000000:
quotient, remainder = divmod( top, bottom )
p2, p1 = p1, p2 + quotient * p1
q2, q1 = q1, q2 + quotient * q1
top, bottom = bottom, remainder

diff = float(p1)/q1 - math.pi
sign = '+'
if diff < 0: sign = '-'
print p1, '/', q1, '\t= pi', sign, abs(diff)

It also illustrates that floating-point output may differ on different
machines, which gives every number-cruncher that warm glow of easy
familiarity <grin>:

approximations to pi
3L / 1L = pi - 0.14159265359
22L / 7L = pi + 0.00126448926735
333L / 106L = pi - 8.32196275291e-05
355L / 113L = pi + 2.66764189405e-07
103993L / 33102L = pi - 5.77890624243e-10
104348L / 33215L = pi + 3.31628058348e-10
208341L / 66317L = pi - 1.22356347276e-10
312689L / 99532L = pi + 2.91433543964e-11
833719L / 265381L = pi - 8.71525074331e-12
1146408L / 364913L = pi + 1.61071156413e-12
4272943L / 1360120L = pi - 4.04121180964e-13

> ... but for those who are afraid of Perl it might actually work to
> compare a few cases of Python and Perl code...

Perhaps more to the point, if you include _any_ comparison of Python &
Perl, it will guarantee a flame war that will keep Python's name active
on the Net for months <snicker> ...