Skip to content

Commit 9b229ed

Browse files
committed
Added doctests for monte_carlo.py
1 parent 27c1840 commit 9b229ed

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

maths/monte_carlo.py

+23-2
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@ def pi_estimator(iterations: int):
1818
4. After all the dots are placed, divide the dots in the circle by the total.
1919
5. Multiply this value by 4 to get your estimate of pi.
2020
6. Print the estimated and numpy value of pi
21+
>>> pi_estimator(1000)
22+
The estimated value of pi is 3.145
23+
The numpy value of pi is 3.141592653589793
24+
The total error is 0.003
2125
"""
2226

2327
# A local function to see if a dot lands in the circle.
@@ -61,8 +65,11 @@ def area_under_curve_estimator(
6165
c. Expected value = average of the function evaluations
6266
4. Estimated value of integral = Expected value * (max_value - min_value)
6367
5. Returns estimated value
68+
>>> def test_function(x):
69+
>>> return x * x
70+
>>> area_under_curve_estimator(1000, test_function)
71+
0.334 (estimated value should be close to 1/3)
6472
"""
65-
6673
return mean(
6774
function_to_integrate(uniform(min_value, max_value)) for _ in range(iterations)
6875
) * (max_value - min_value)
@@ -77,12 +84,19 @@ def area_under_line_estimator_check(
7784
1. Calls "area_under_curve_estimator" function
7885
2. Compares with the expected value
7986
3. Prints estimated, expected and error value
87+
>>> area_under_line_estimator_check(1000)
88+
******************
89+
Estimating area under y=x where x varies from 0.0 to 1.0
90+
Estimated value is 0.332
91+
Expected value is 0.5
92+
Total error is 0.168
93+
******************
8094
"""
8195

8296
def identity_function(x: float) -> float:
8397
"""
8498
Represents identity function
85-
>>> [function_to_integrate(x) for x in [-2.0, -1.0, 0.0, 1.0, 2.0]]
99+
>>> [identity_function(x) for x in [-2.0, -1.0, 0.0, 1.0, 2.0]]
86100
[-2.0, -1.0, 0.0, 1.0, 2.0]
87101
"""
88102
return x
@@ -103,6 +117,13 @@ def identity_function(x: float) -> float:
103117
def pi_estimator_using_area_under_curve(iterations: int) -> None:
104118
"""
105119
Area under curve y = sqrt(4 - x^2) where x lies in 0 to 2 is equal to pi
120+
>>> pi_estimator_using_area_under_curve(1000)
121+
******************
122+
Estimating pi using area_under_curve_estimator
123+
Estimated value is 3.141
124+
Expected value is 3.141592653589793
125+
Total error is 0.0004
126+
******************
106127
"""
107128

108129
def function_to_integrate(x: float) -> float:

0 commit comments

Comments
 (0)