Finding pi with a three-line function [Python / Monte Carlo method]

What is this article

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. ** **

version information

python: 3.7.3 numpy: 1.17.4

code

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

Commentary

The method of calculating pi by the Monte Carlo method is known.

The first line

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]]
"""
2nd line

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]
"""
3rd line

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

Execution result

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

Finding pi with a three-line function [Python / Monte Carlo method]
#Monte Carlo method to find pi using Python
Simulate Monte Carlo method in Python
Create a Python function decorator with Class
Monte Carlo method
Try implementing the Monte Carlo method in Python
Kernel Method with Python
[Practice] Make a Watson app with Python! # 2 [Translation function]
[Python] A program for finding the Fibonacci sequence (recursive function, divide-and-conquer method, dynamic programming method)
Introduction to Monte Carlo Method
Create a Mastodon bot with a function to automatically reply with Python
[Python] Calculation method with numpy
Associate Python Enum with a function and make it Callable
Create a directory with python
Control the motor with a motor driver using python on Raspberry Pi 3!
[Road to Python Intermediate] Call a class instance like a function with __call__
[Introduction to Python] How to split a character string with the split function
[Python 3.8 ~] How to define a recursive function smartly with a lambda expression
[Statistics] Visualize and understand the Hamiltonian Monte Carlo method with animation.
A function that measures the processing time of a method in python
[Python] I made an image viewer with a simple sorting function.
Solve the Python knapsack problem with a branch and bound method
[Note] Using 16x2-digit character LCD (1602A) from Python with Raspberry Pi
[Python] What is a zip function?
[Python] What is a with statement?
Solve ABC163 A ~ C with Python
Operate a receipt printer with python
A python graphing manual with Matplotlib.
Use vl53l0x with Raspberry Pi (python)
Solve ABC166 A ~ D with Python
Create a virtual environment with Python!
I made a fortune with Python.
[Python] Make the function a lambda function
Make a recommender system with python
Estimating π by Monte Carlo method
[Python] Generate a password with Slackbot
Solve ABC162 A ~ C with Python
Solve ABC167 A ~ C with Python
Solve ABC158 A ~ C with Python
Let's make a graph with python! !!
[Python] Difference between function and method
[Python] Inherit a class with class variables
I made a daemon with Python
Using a webcam with Raspberry Pi
Write a batch script with Python3.5 ~
Detect analog signals with A / D converter using python on Raspberry Pi 3!
[Python] Explains how to use the range function with a concrete example
[Python + PHP] Make a temperature / humidity / barometric pressure monitor with Raspberry Pi
I tried to make a traffic light-like with Raspberry Pi 4 (Python edition)
Hit a method of a class instance with the Python Bottle Web API
Create a Python multi-user platform with JupyterHub + JupyterLab on Rapsberry Pi 3B +!
[Introduction to Python] How to write a character string with the format function
[Competition Pro] Let Python play a stone-picking game with no winning method
Spiral book in Python! Python with a spiral book! (Chapter 14 ~)
Creating a simple PowerPoint file with Python
[Python] A program that creates stairs with #
Building a Python3 environment with Amazon Linux2
Let's make a shiritori game with Python
Install Python as a Framework with pyenv
Build a blockchain with Python ① Create a class
Precautions when pickling a function in python