How to find the pi with a three-line function and its explanation.
As a rule, ** do not force the code to be compressed, but write it in a natural way. ** **
python: 3.7.3 numpy: 1.17.4
calcPi.py
import numpy as np
def calcPi(n):
points = np.random.uniform(0.0, 1.0, (n, 2))
inner = np.hypot(points[:,0], points[:,1]) < 1
return inner.mean() * 4
mean ()
.The method of calculating pi by the Monte Carlo method is known.
np.random.uniform
stores uniform random numbers in the range 0 to 1 in an array of n rows and 2 columns.
Each row corresponds to a point on the plane.
The first line
points = np.random.uniform(0.0, 1.0, (n, 2))
"""
For example n=When
[[ 0.6906296 0.20549271]
[ 0.13386813 0.77204275]
[ 0.5970941 0.49659941]
[ 0.92884413 0.37740529]
[ 0.49212498 0.13915062]
[ 0.69357975 0.23229706]
[ 0.14287715 0.14076891]
[ 0.20199753 0.49663344]
[ 0.90105166 0.87612407]
[ 0.19636323 0.39813228]]
"""
np.hypot (x, y)
is from the origin of the point (x, y)
Returns the distance.
points [:, 0]
is an array extracted from the 0th column of points
, that is, the size of the x coordinate of each point.
points [:, 1]
is also the y coordinate of each point.
At the end, we are doing <1
, so if the contents of the array is less than 1, it will change to True, and if it is 1 or more, it will change to False.
In other words, if the distance from the origin is less than 1, you get an array that is True, and if it is more than 1, you get an array that is False.
2nd line
inner = np.hypot(points[:,0], points[:,1]) < 1
"""
For example, n=When it is 10,
inner == [True True True True False True False True True False]
"""
Dividing the number of points whose distance from the origin is less than 1 by the total number of points gives an approximate value of π / 4
.
It takes the average of the inner and returns 4 times.
(As you can see in Comment, True and False
are converted to 1 and 0
at the time of calculation, respectively.)
4th line
return inner.mean() * 4
This is the execution result when seed
is set to 0.
print(calcPy(10)) # => 2.8
print(calcPi(100)) # => 3.32
print(calcPi(1000)) # => 3.302
print(calcPi(10000)) # => 3.1544
print(calcPi(100000)) # => 3.13228
print(calcPi(1000000)) # => 3.142204
print(calcPi(10000000)) # => 3.1421468
print(calcPi(100000000)) # => 3.14170808
that's all. Please let me know if you have any mistakes.
Recommended Posts