Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- from scipy.integrate import odeint
- from scipy.integrate import quad
- def f(y,x):
- dydx = -x/y
- return dydx
- g = lambda x: -(-x**2 + 25)**(0.5)
- def RK4OdeSys(f,c,x):
- H = x[1] - x[0]
- N = len(x)
- z = np.zeros(N)
- z[0] = c
- for k in range(0,N-1):
- k1 = f(z[k],x[k])
- k2 = f(z[k]+ ((H) * (k1/2)), x[k] + (H/2) )
- k3 = f(z[k]+ (H * (k2/2)), x[k] + (H/2) )
- k4 = f(z[k]+ (H * k3) , x[k] + H )
- z[k+1] = z[k] + ((H/6) * (k1 + 2*k2 + 2*k3 + k4) )
- return z
- H = 0.01
- x = np.arange(4,5,H)
- z0 = -3
- z_odeint = odeint(f,z0,x)
- z_rk_4 = RK4OdeSys(f,z0,x)
- z_actual = g(x)
- z_odeint = z_odeint.reshape(100,)
- fig = plt.figure(1,figsize=(8,5))
- er1 = abs(z_actual - z_odeint)
- plt.plot(x,er1)
- er2 = abs(z_actual - z_rk_4)
- plt.plot(x,er2,"r")
- plt.xlabel("x")
- plt.ylabel("y")
- plt.legend(["exact vs odeint","Exact vs Rung-Kutta"])
- plt.title("Comparision of approximation errors")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement