[LUAU] doing 'e'
Tim Newsham
newsham at lava.net
Wed Nov 30 10:43:04 PST 2005
> Lets see a perl/python/... equivalent to this lisp exercise for obtaining
> 'e':
[...]
> Euler's number, 'e', is approximately 2.7182818284590452354, and this is a
> highly-inefficient way to extract it, but
> the function does tend toward 'e'.)
>
> Jim
If you like this kind of stuff, you'd probably get a kick out of
Doug McIlroy's "The Music of Streams", available on his home page:
http://www.cs.dartmouth.edu/~doug/
I toyed with the code in python a little:
http://lava.net/~newsham/x/machine/powerseries.py
http://lava.net/~newsham/x/machine/powerseries2.py
but neither is as elegant as his (pseudo-) haskell implementation
Heres your python code:
#!/usr/bin/python
import random
uniform = random.random # gratuitous rename
def waitTime() :
"""Return the number of uniform variates whose sum just exceeds 1."""
sum,times = 0,0
while sum <= 1.0 :
sum,times = sum+uniform(), times+1
return times
def repeat(n, f, *args, **kwargs) :
"""Return the results of running a function n times."""
return [f(*args, **kwargs) for n in xrange(n)]
def average(l) :
"""
Return the average of a list.
Raise an exception for empty lists.
"""
return float(sum(l)) / len(l)
# show some waitTime results
print "Some waitTimes", repeat(10, waitTime)
# show averages for increasing lengths of repeat(waitTime)
print "average waitTimes", [average(repeat(n, waitTime)) for n in 1, 10, 100, 1000, 10000, 100000]
Tim Newsham
http://www.lava.net/~newsham/
More information about the LUAU
mailing list