MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / area_under_curve_estimator

Function area_under_curve_estimator

maths/monte_carlo.py:42–68  ·  view source on GitHub ↗

An implementation of the Monte Carlo method to find area under a single variable non-negative real-valued continuous function, say f(x), where x lies within a continuous bounded interval, say [min_value, max_value], where min_value and max_value are finite numbers

(
    iterations: int,
    function_to_integrate: Callable[[float], float],
    min_value: float = 0.0,
    max_value: float = 1.0,
)

Source from the content-addressed store, hash-verified

40
41
42def area_under_curve_estimator(
43 iterations: int,
44 function_to_integrate: Callable[[float], float],
45 min_value: float = 0.0,
46 max_value: float = 1.0,
47) -> float:
48 """
49 An implementation of the Monte Carlo method to find area under
50 a single variable non-negative real-valued continuous function,
51 say f(x), where x lies within a continuous bounded interval,
52 say [min_value, max_value], where min_value and max_value are
53 finite numbers
54 1. Let x be a uniformly distributed random variable between min_value to
55 max_value
56 2. Expected value of f(x) =
57 (integrate f(x) from min_value to max_value)/(max_value - min_value)
58 3. Finding expected value of f(x):
59 a. Repeatedly draw x from uniform distribution
60 b. Evaluate f(x) at each of the drawn x values
61 c. Expected value = average of the function evaluations
62 4. Estimated value of integral = Expected value * (max_value - min_value)
63 5. Returns estimated value
64 """
65
66 return mean(
67 function_to_integrate(uniform(min_value, max_value)) for _ in range(iterations)
68 ) * (max_value - min_value)
69
70
71def area_under_line_estimator_check(

Calls 2

meanFunction · 0.85
function_to_integrateFunction · 0.85

Tested by

no test coverage detected