TheAlgorithms-Python

Форк
0
/
pi_monte_carlo_estimation.py 
67 строк · 2.0 Кб
1
import random
2

3

4
class Point:
5
    def __init__(self, x: float, y: float) -> None:
6
        self.x = x
7
        self.y = y
8

9
    def is_in_unit_circle(self) -> bool:
10
        """
11
        True, if the point lies in the unit circle
12
        False, otherwise
13
        """
14
        return (self.x**2 + self.y**2) <= 1
15

16
    @classmethod
17
    def random_unit_square(cls):
18
        """
19
        Generates a point randomly drawn from the unit square [0, 1) x [0, 1).
20
        """
21
        return cls(x=random.random(), y=random.random())
22

23

24
def estimate_pi(number_of_simulations: int) -> float:
25
    """
26
    Generates an estimate of the mathematical constant PI.
27
    See https://en.wikipedia.org/wiki/Monte_Carlo_method#Overview
28

29
    The estimate is generated by Monte Carlo simulations. Let U be uniformly drawn from
30
    the unit square [0, 1) x [0, 1). The probability that U lies in the unit circle is:
31

32
        P[U in unit circle] = 1/4 PI
33

34
    and therefore
35

36
        PI = 4 * P[U in unit circle]
37

38
    We can get an estimate of the probability P[U in unit circle].
39
    See https://en.wikipedia.org/wiki/Empirical_probability by:
40

41
        1. Draw a point uniformly from the unit square.
42
        2. Repeat the first step n times and count the number of points in the unit
43
            circle, which is called m.
44
        3. An estimate of P[U in unit circle] is m/n
45
    """
46
    if number_of_simulations < 1:
47
        raise ValueError("At least one simulation is necessary to estimate PI.")
48

49
    number_in_unit_circle = 0
50
    for _ in range(number_of_simulations):
51
        random_point = Point.random_unit_square()
52

53
        if random_point.is_in_unit_circle():
54
            number_in_unit_circle += 1
55

56
    return 4 * number_in_unit_circle / number_of_simulations
57

58

59
if __name__ == "__main__":
60
    # import doctest
61

62
    # doctest.testmod()
63
    from math import pi
64

65
    prompt = "Please enter the desired number of Monte Carlo simulations: "
66
    my_pi = estimate_pi(int(input(prompt).strip()))
67
    print(f"An estimate of PI is {my_pi} with an error of {abs(my_pi - pi)}")
68

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.