0% found this document useful (0 votes)
15 views10 pages

Exercise 7

Uploaded by

ranjehora
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views10 pages

Exercise 7

Uploaded by

ranjehora
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Øving 7 Oppgave 1

import numpy as np
import matplotlib.pyplot as plt

def f(t, y):


return -2 * t * y

def runge_kutta_4th_order(f, y0, t0, t_end, h):


n_steps = int((t_end - t0) / h)
t_values = np.linspace(t0, t_end, n_steps + 1)
y_values = np.zeros(n_steps + 1)
y_values[0] = y0 # initial

for i in range(n_steps):
t_n = t_values[i]
y_n = y_values[i]

k1 = f(t_n, y_n)
k2 = f(t_n + h/2, y_n + h/2 * k1)
k3 = f(t_n + h/2, y_n + h/2 * k2)
k4 = f(t_n + h, y_n + h * k3)

y_values[i+1] = y_n + h/6 * (k1 + 2*k2 + 2*k3 + k4)

return t_values, y_values

y0 = 1 # initial
t0 = 0 # start
t_end = 2 # end
h = 0.1 # step

t_values, y_values = runge_kutta_4th_order(f, y0, t0, t_end, h)

def analytic_solution(t):
return np.exp(-t**2)

y_exact = analytic_solution(t_values)

plt.plot(t_values, y_values, label="Numerical (RK4)", marker='o')


plt.plot(t_values, y_exact, label="Analytical", linestyle='--')
plt.xlabel('t')
plt.ylabel('y(t)')
plt.legend()
plt.title('4th Order Runge-Kutta vs Analytical Solution')
plt.grid(True)
plt.show()
Oppgave 1B

def compute_error(f, y0, t0, t_end, h):


t_values, y_numerical = runge_kutta_4th_order(f, y0, t0, t_end, h)
y_exact = analytic_solution(t_values)
error = np.abs(y_numerical - y_exact)
return np.max(error)

h_values = [0.1, 0.05, 0.025, 0.0125]


errors = []

for h in h_values:
error = compute_error(f, y0, t0, t_end, h)
errors.append(error)

plt.loglog(h_values, errors, marker='o')


plt.xlabel('Step size (h)')
plt.ylabel('Max Error')
plt.title('Convergence Order of 4th Order Runge-Kutta Method')
plt.grid(True)
plt.show()

for i in range(1, len(errors)):


error_ratio = errors[i-1] / errors[i]
print(f"Error ratio (h{i-1}/h{i}): {error_ratio:.4f}")
Error ratio (h0/h1): 17.8884
Error ratio (h1/h2): 16.9222
Error ratio (h2/h3): 16.4525

Oppgave 2A)

f = lambda t, y: 2 / t * y

t0, tend = 1, 2
y0 = 1
N = 10

h = (tend - t0) / N

y = np.zeros(N + 1)
t = np.zeros(N + 1)

y[0] = y0
t[0] = t0

for n in range(N):
k1 = f(t[n], y[n])
k2 = f(t[n] + 0.5 * h, y[n] + 0.5 * h * k1)
k3 = f(t[n] + 0.75 * h, y[n] + 0.75 * h * k2)
y[n + 1] = y[n] + h * (2 * k1 + 3 * k2 + 4 * k3) / 9
t[n + 1] = t[n] + h

print('t =', t)
print('y =', y)

t = [1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2. ]
y = [1. 1.20996678 1.43993271 1.6898975 1.95986092 2.24982281
2.55978304 2.88974151 3.23969813 3.60965285 3.99960561]

Oppgave 2B) Koden løser en Første orden ODE = y'(t)=2/t * y(t), y(1) = 1

Oppgave 2D)

f = lambda t, y: 2 / t * y
t0, tend = 1, 2
y0 = 1
N = 10
h = (tend - t0) / N

y = np.zeros(N + 1)
t = np.zeros(N + 1)
y[0] = y0
t[0] = t0

k1 = f(t[0], y[0])
k2 = f(t[0] + 0.5 * h, y[0] + 0.5 * h * k1)
k3 = f(t[0] + 0.75 * h, y[0] + 0.75 * h * k2)
y[1] = y[0] + h * (2 * k1 + 3 * k2 + 4 * k3) / 9

y[:2] # First two elements of y

array([1. , 1.20996678])

Oppgave 4 C)

k1 = 100
k2 = 200
m1 = 10
m2 = 5

def f(t, y):


y1, y2, y3, y4 = y
dy1_dt = y2
dy2_dt = (-k1 * y1 + k2 * (y3 - y1)) / m1
dy3_dt = y4
dy4_dt = (-k2 * (y3 - y1)) / m2
return np.array([dy1_dt, dy2_dt, dy3_dt, dy4_dt])

def euler_method(f, t0, y0, h, steps):


y = np.zeros((steps + 1, len(y0)))
t = np.zeros(steps + 1)
y[0] = y0
t[0] = t0
for i in range(steps):
y[i+1] = y[i] + h * f(t[i], y[i])
t[i+1] = t[i] + h
return t, y

def heun_method(f, t0, y0, h, steps):


y = np.zeros((steps + 1, len(y0)))
t = np.zeros(steps + 1)
y[0] = y0
t[0] = t0
for i in range(steps):
y_pred = y[i] + h * f(t[i], y[i])
y[i+1] = y[i] + (h/2) * (f(t[i], y[i]) + f(t[i+1], y_pred))
t[i+1] = t[i] + h
return t, y

y0 = [0, 1, 0, 1]
t0 = 0
t_end = 3

def plot_results(t_euler, y_euler, t_heun, y_heun, step_size):


plt.figure(figsize=(10, 6))
plt.plot(t_euler, y_euler[:, 0], label='Euler: u(t)',
linestyle='--')
plt.plot(t_euler, y_euler[:, 2], label='Euler: v(t)',
linestyle='--')
plt.plot(t_heun, y_heun[:, 0], label='Heun: u(t)')
plt.plot(t_heun, y_heun[:, 2], label='Heun: v(t)')
plt.title(f'Solution using step size h = {step_size}')
plt.xlabel('Time')
plt.ylabel('Displacement')
plt.legend()
plt.grid()
plt.show()

# Testing different step sizes


for h in [0.1, 0.01, 0.001]:
steps = int((t_end - t0) / h)

# Euler's method
t_euler, y_euler = euler_method(f, t0, y0, h, steps)
# Heun's method
t_heun, y_heun = heun_method(f, t0, y0, h, steps)

# Plot the results


plot_results(t_euler, y_euler, t_heun, y_heun, h)
Oppgave 4D)
def compute_energy(y, k1, k2, m1, m2):
u = y[:, 0]
u_prime = y[:, 1]
v = y[:, 2]
v_prime = y[:, 3]
E = (0.5 * m1 * u_prime**2) + (0.5 * m2 * v_prime**2) + (0.5 * k1
* u**2) + (0.5 * k2 * (v - u)**2)
return E

def plot_energy_conservation(t, E_euler, E_heun, step_size):


plt.figure(figsize=(10, 6))
plt.plot(t, E_euler, label='Euler Energy', linestyle='--')
plt.plot(t, E_heun, label='Heun Energy')
plt.title(f'Energy Conservation using step size h = {step_size}')
plt.xlabel('Time')
plt.ylabel('Total Energy')
plt.legend()
plt.grid()
plt.show()

for h in [0.1, 0.01, 0.001]:


steps = int((t_end - t0) / h)

# Euler's method
t_euler, y_euler = euler_method(f, t0, y0, h, steps)
E_euler = compute_energy(y_euler, k1, k2, m1, m2)

# Heun's method
t_heun, y_heun = heun_method(f, t0, y0, h, steps)
E_heun = compute_energy(y_heun, k1, k2, m1, m2)

# Plot energy conservation


plot_energy_conservation(t_heun, E_euler, E_heun, h)

You might also like