I've written solution of how to calculate pi number in python in one line:
def calc_pi(n=100):
return 4.0 * sum([1 for i in range(n) if hypot(random(), random()) < 1]) / (n + 1)
I would like to know if there is a better solution for that and how to make it simpler?
P.S. I want to practice complex one-line functions, list comprehensions etc. Monte Carlo method is just an example.
sum([1 for i in range(n) if hypot(random(), random()) < 1]) / n
will tend to atan(1)
for large n
, so you might as well calculate it directly:
>>> import math
>>> 4 * math.atan(1)
3.141592653589793
It at least looks like your formula and doesn't explicitely use math.pi
.
By the way, I don't think you should divide by n+1
but by n
. range(n)
has n
elements.
Also, you don't need to create a huge list just to calculate its sum. sum
works fine with a generator.
I guess your hypot
function uses sqrt
. No need for it, since you're comparing to 1
and sqrt(1) == 1
:
>>> from random import random
>>> n = 10000000
>>> 4.0 * sum(1 for i in range(n) if (random()**2 + random()**2) <= 1) / n
3.1418616
As mentioned by @Blender, you could also sum booleans:
>>> 4.0 * sum((random()**2 + random()**2) <= 1 for _ in range(n)) / n
3.1417656
Finally, there are better methods. This one is slow-ish, but it's concise and deterministic:
>>> 4 * sum(1.0/(2*i + 1)*(-1)**i for i in range(1000000))
3.1415916535897743
There are others, faster methods.