Using the random number of Python to solve mathematical problems __python

Source: Internet
Author: User

In the QQ group to see a primary school math problem:

Forgive me is not witty pupil (I believe there must be a simple method), also do not mind the integration of advanced mathematics method ... So I want to use the program to solve it, do not want to cost brain. Then came the idea of a classic algorithm: Monte Carlo method, the specific reference to the 20th century ten great algorithms.

The key of this problem is to find the area of the pseudo triangle in the upper right corner. This will solve the problem. Look at the square on the right side of the right square alone, the red box part of the figure below ~ ~

produces two random numbers x and y with a range of [0,5]. Then use the simple distance comparison to see if this random point falls within the triangle of the shadow. Repeat this process n times, when the number of repetitions is close to infinity, the result is more accurate. I have taken 100000 here, in fact, the precision has 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 results are:

21.3247636603
[finished in 0.2s]

Don't know the correct answer is wrong, but this method is very cool.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.