Use Python's random numbers to solve math problems

In the qq group, I saw a math problem in elementary school:

Write picture description here

Forgive me for not being a witty primary school student (I believe there must be a simple method), and I also dislike the integral method of advanced mathematics. . . So I want to solve it with a program, and I don't want to bother my brain. So I thought of a classic algorithm: the Monte Carlo method. For details, you can refer to the top ten great algorithms of the 20th century .

The key to this question is to find the area of ​​the pseudo triangle in the upper right corner. In this way, the problem is easily solved. Look at the quarter of the square on the upper right of the square on the right alone, the red frame part in the picture below~~

Write picture description here

Generate two random numbers x and y in the range [0,5]. Then apply a simple distance comparison to see if this random point falls within the shaded triangle. Repeat this process n times, when the number of repetitions is close to infinity, the result is more accurate. I took 100,000 here, but the accuracy has actually reached 0.01.

import random
import math

count = 0
for i in range(100000):
    x = random.random() * 5
    y = random.random() * 5
    if math.sqrt(x**2 + y**2) > 5 and (y < 0.5 * x + 2.5):
        count = count + 1
result = 100 - math.pi * 25 - count / 100000.0
print result

In this way, the calculated result is:

21.3247636603
[Finished in 0.2s]

I don't know if the correct answer is wrong, but this method is very cool.

Guess you like

Origin blog.csdn.net/qxconverse/article/details/52077830