当前位置:网站首页>Using Monte Carlo method to calculate pi

Using Monte Carlo method to calculate pi

2022-06-22 06:18:00 fire2fire2

Ideas

The area of a square is :1
The area of the circle is :2
The area of a circle is... Larger than that of a square :π / 4
Use Monte Carlo method to scatter points randomly in the square , The point falling in the circle / The point falling in the square ( All points ), It's about equal to the area of the circle / The square area = π / 4
 Ideas
The code is implemented in the first quadrant 1/4 Circle as an example .

Code

import random
 
def count_pi(n):
    # Here we use 1/4 Circle writing code logic 
    i = 0
    count = 0
    # n  Is the total number of incoming points 
    while i < n:
        #  Randomly generated x,y coordinate 
        # random.random() Used to generate a 0 To 1 The number of random characters of : 0 <= n < 1.0
        x = random.random()
        y = random.random()
        #  If x square  + y square  < 1, Description in circle 
        if (pow(x, 2) + pow(y, 2)) < 1:
            count += 1
        i += 1
    # π The value of is :4 * ( The point falling in the circle / Total point )
    return 4 * (count / n)
 
 
pi = count_pi(100000)
print(pi)

Running results

function 100 Time , Average. .
 Running results

Mont · Carol's method (Monte Carlo method), Also known as statistical simulation method , A kind of very important numerical calculation method guided by the theory of probability and statistics . It means using random numbers ( Or more common pseudo-random numbers ) To solve a lot of computational problems .

原网站

版权声明
本文为[fire2fire2]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220604445072.html