Skip to content

Instantly share code, notes, and snippets.

@redwrasse
Created July 2, 2020 01:34
Show Gist options
  • Save redwrasse/04d4dad871f398a7df9ab15822ded5cf to your computer and use it in GitHub Desktop.
Save redwrasse/04d4dad871f398a7df9ab15822ded5cf to your computer and use it in GitHub Desktop.
monte carlo integration of functions on subset of the real line
"""
Monte Carlo integration of functions on subsets of the real line,
using uniform probability distributions
"""
import math
import random
def montecarlo(f, g, a, b):
"""
:param f: the integral function
:param g: the integrand function
:param a: integration lower point
:param b: integration upper point
:return: None
"""
if f is not None:
actual = f(b) - f(a)
print(f"actual integral: {actual}")
else:
print("No analytical integral given. Cannot compute actual integral compare.")
N = 10**6
M = 10
sm = 0.
for j in range(M):
for i in range(N):
x = random.uniform(a, b)
sm += g(x)
computed = 1.0 * sm / (N*(j+1)) * (b - a)
rel_err = abs(computed - actual) / actual if f is not None else 'n/a'
print(f"finished. computed {computed} rel. error: {rel_err}")
print('-' * 4)
def example1():
f = math.sin
g = math.cos
a, b = 0.0, math.pi / 2
montecarlo(f, g, a, b)
def example2():
f = math.log
g = lambda x: 1. / x
a, b = 6., 11.
montecarlo(f, g, a, b)
example1()
example2()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment