Professional Documents
Culture Documents
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
import sympy as sym
import math
def integral_ln_x(x):
return math.log(x)
a = 1
b = 3
approx_integral = midpoint(integral_ln_x, a, b)
print("Approximate integral of ln(x) from 1 to 3 using the Midpoint
Rule:", approx_integral)
print("Exact integral of ln(x) from 1 to 3 using the Midpoint Rule:",
exact_integral)
Exercise 1b
import math
def integral_ln_x(x):
return math.log(x)
a = 1
b = 3
approx_integral = trapez(integral_ln_x, a, b)
print("Approximate integral of ln(x) from 1 to 3 using the Trapezoidal
Rule:", approx_integral)
print("Exact integral of ln(x) from 1 to 3 using the Trapezoidal
Rule:", exact_integral)
Exercise 1c
import math
def integral_ln_x(x):
return math.log(x)
a = 1
b = 3
n=8
approx_integral = simpson(integral_ln_x, a, b, n)
print("Approximate integral of ln(x) from 1 to 3 using the Simpson
Rule:", approx_integral)
print("Exact integral of ln(x) from 1 to 3 using the Trapezoidal
Rule:", exact_integral)
Exercise 1d
import numpy as np
def compositeMidpoint(f, a, b, n, demoMode=False):
h = (b-a)/n
x = np.linspace(a+h/2, b-h/2, n)
if demoMode:
print(f"With {a=}, {b=}, {n=}, {h=} and the nodes are {x}")
M_n = sum(f(x)) * h
return M_n
def f(x): return 1/x**2
a=1
b=3
I_exact = 2.0/3.0
Exercise 1e
import math
def func(x):
return 1/(1+x**2)
Exercise 1f
import math
Exercise 2
import numpy as np
Exercise 3
a = -2
b = 2
n = 6
approximate_value = montecarlo(f, a, b, n)
exact_value = (b - a) * np.sqrt(2 / (a * b * np.pi)) * np.exp(-(a ** 2
+ b ** 2) / 4)
Exercise 4
a = -2
b = 2
n = 5
approximate_value = montecarlo(f, a, b, n)
exact_value = (b - a) * np.sqrt(2 / (a * b * np.pi)) * np.exp(-(a ** 2
+ b ** 2) / 4)
Exercise 5
def montecarlo(f, a, b, n):
random_points = np.random.rand(n) * (b - a) + a
integral_approx = n * np.mean([abs(f(x)) for x in random_points])
integral_exact = (b - a) * np.sqrt(2 / (a * b * np.pi)) * np.exp(-(a ** 2 + b ** 2) / 4)
return integral_approx
def f(x):
return 10 * np.exp(-x ** 2) - 6
a = -2
b=2
n=3
approximate_value = montecarlo(f, a, b, n)
exact_value = (b - a) * np.sqrt(2 / (a * b * np.pi)) * np.exp(-(a ** 2 + b ** 2) / 4)