You are on page 1of 7

Exercise 1a

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)

# Calculate the exact integral of ln(x) from 1 to 3


exact_integral = math.log(3) - math.log(1)
print("Exact integral of ln(x) from 1 to 3:", exact_integral)

def midpoint(f, a, b):


# Calculate the midpoint
h = (b - a) / 2
c = a + h

# Compute the integral approximation


return h * (f(c) + f(b) + f(a))

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)

# Calculate the exact integral of ln(x) from 1 to 3


exact_integral = math.log(3) - math.log(1)
print("Exact integral of ln(x) from 1 to 3:", exact_integral)

def trapez(f, a, b):


# Compute the integral approximation using the Trapezoidal Rule
n = int((b - a) / 0.02) # Choose a step size and adjust the number
of intervals accordingly
h = (b - a) / n
s = f(a) / 2 + sum(f(a + i * h) for i in range(1, n)) + f(b) / 2
return h * s

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)

# Calculate the exact integral of ln(x) from 1 to 3


exact_integral = math.log(3) - math.log(1)
print("Exact integral of ln(x) from 1 to 3:", exact_integral)

def simpson(f, a, b, n):


# Compute the integral approximation using the Simpson Rule
h = (b - a) / n
s = f(a) / 3 + sum(2 * f(a + i * h) for i in range(1, n, 3)) + f(b)
/ 3
return h * s

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

M_5 = compositeMidpoint(f, a, b, 5, demoMode=True)


error = M_5 - I_exact
print(f"{M_5=}, {error=}")
print()
M_100 = compositeMidpoint(f, a, b, 100, demoMode=False)
error = M_100 - I_exact
print(f"{M_100=}, {error=}")

Exercise 1e

import math
def func(x):
return 1/(1+x**2)

# Define the single Trapezoidal rule for one subinterval


def trap_rule(f, a, b, h):
return h/ 2 * (f(a) + f(b)) + h*f(((a-1*h)+(a*h))/2)

# Define the composite Trapezoidal rule function


def comp_trapz(f, a, b, n):
h = (b - a) / n
return sum(trap_rule(f, a, b, h) for _ in range(n))

# Compute the integral of ln(x) from 1 to 3 with 4 subintervals


f = lambda x: math.log(x)
a = 1
b = 3
n = 5
exact_value = math.log(b) - math.log(a)
approximate_value = comp_trapz(f, a, b, n)
print("Exact value:", exact_value)
print("Approximate value:", approximate_value)

Exercise 1f

import math

# Define the single Simpson rule for one subinterval


def simpson_rule(f, a, b, h):
return (h / 6) * (f(a) + 4 * f((a + b) / 2) + f(b))

# Define the composite Simpson rule function


def comp_simpson(f, a, b, n):
h = (b - a) / n
return sum(simpson_rule(f, a, b, h) for _ in range(n))

# Compute the integral of ln(x) from 1 to 3 with 4 subintervals


f = lambda x: math.log(x)
a = 1
b = 3
n = 4
exact_value = math.log(b) - math.log(a)
approximate_value = comp_simpson(f, a, b, n)

print("Exact value:", exact_value)


print("Approximate value:", approximate_value)

Exercise 2

import numpy as np

def gauss(f, a, b, n):


# Define the nodes and weights for Gauss quadrature
if n == 1:
nodes = [0]
weights = [2]
elif n == 2:
nodes = [-1/np.sqrt(3), 1/np.sqrt(3)]
weights = [1, 1]
elif n == 3:
nodes = [-np.sqrt(3/5), 0, np.sqrt(3/5)]
weights = [5/9, 8/9, 5/9]
else:
raise ValueError("Unsupported number of nodes")

# Transform nodes from [-1, 1] to [a, b]


nodes_transformed = [(b-a)/2 * node + (b+a)/2 for node in nodes]

# Calculate the approximation using Gauss quadrature formula


integral_approx = sum([weights[i] * f(nodes_transformed[i]) for i
in range(n)]) * (b-a)/2
return integral_approx

# Define the function to integrate


def ln_x(x):
return np.log(x)

# Define the boundaries


a = 1
b = 3

# Compute the exact integral


exact_integral = np.log(b) - np.log(a)

# Compute the approximate integrals with n = 1, 2, and 3


n_values = [1, 2, 3]
for n in n_values:
approx_integral = gauss(ln_x, a, b, n)
print(f"For n = {n}:")
print("Exact integral:", exact_integral)
print("Approximate integral:", approx_integral)
print()

Exercise 3

def montecarlo(f, a, b, n):


random_points = np.random.rand(n) * (b - a) + a
integral_approx = n * np.mean([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 np.exp(-x ** 2)

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)

print(f"Exact Value: {exact_value}")


print(f"Approximate Value: {approximate_value}")

Exercise 4

def montecarlo(f, a, b, n):


random_points = np.random.rand(n) * (b - a) + a
integral_approx = n * np.mean([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 np.exp(-x ** 2)

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)

print(f"Exact Value: {exact_value}")


print(f"Approximate Value: {approximate_value}")

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)

print(f"Exact Value: {exact_value}")


print(f"Approximate Value: {approximate_value}")

You might also like