Skip to content

Commit b36e46b

Browse files
authoredFeb 22, 2020
extend estimation of area under curve of y=x using monte carlo simulation to any given lower and upper bound (TheAlgorithms#1784)
* extend estimation of area under curve of y=x using monte carlo simulation to any given lower and upper bound * remove doctest
1 parent 6d7cbda commit b36e46b

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed
 

‎maths/monte_carlo.py

+14-9
Original file line numberDiff line numberDiff line change
@@ -42,29 +42,34 @@ def area_under_line_estimator(iterations: int,
4242
An implementation of the Monte Carlo method to find area under
4343
y = x where x lies between min_value to max_value
4444
1. Let x be a uniformly distributed random variable between min_value to max_value
45-
2. Expected value of x = integration of x from min_value to max_value
45+
2. Expected value of x = (integration of x from min_value to max_value) / (max_value - min_value)
4646
3. Finding expected value of x:
4747
a. Repeatedly draw x from uniform distribution
4848
b. Expected value = average of those values
49-
4. Actual value = 1/2
49+
4. Actual value = (max_value^2 - min_value^2) / 2
5050
5. Returns estimated value
5151
"""
52-
return mean(uniform(min_value, max_value) for _ in range(iterations))
52+
return mean(uniform(min_value, max_value) for _ in range(iterations)) * (max_value - min_value)
5353

5454

55-
def area_under_line_estimator_check(iterations: int) -> None:
55+
def area_under_line_estimator_check(iterations: int,
56+
min_value: float=0.0,
57+
max_value: float=1.0) -> None:
5658
"""
5759
Checks estimation error for area_under_line_estimator func
5860
1. Calls "area_under_line_estimator" function
5961
2. Compares with the expected value
6062
3. Prints estimated, expected and error value
6163
"""
62-
estimate = area_under_line_estimator(iterations)
64+
65+
estimated_value = area_under_line_estimator(iterations, min_value, max_value)
66+
expected_value = (max_value*max_value - min_value*min_value) / 2
67+
6368
print("******************")
64-
print("Estimating area under y=x where x varies from 0 to 1")
65-
print("Expected value is ", 0.5)
66-
print("Estimated value is ", estimate)
67-
print("Total error is ", abs(estimate - 0.5))
69+
print("Estimating area under y=x where x varies from ",min_value, " to ",max_value)
70+
print("Estimated value is ", estimated_value)
71+
print("Expected value is ", expected_value)
72+
print("Total error is ", abs(estimated_value - expected_value))
6873
print("******************")
6974

7075

0 commit comments

Comments
 (0)
Please sign in to comment.