Advertisement
yusufbrima

ODEGraph

Nov 14th, 2020 (edited)
906
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.98 KB | None | 0 0
  1. import numpy as np
  2. from scipy.integrate import odeint
  3. from scipy.integrate import quad
  4. def f(y,x):
  5.     dydx = -x/y
  6.     return dydx
  7.  
  8. g = lambda x: -(-x**2 + 25)**(0.5)
  9. def RK4OdeSys(f,c,x):
  10.     H = x[1] - x[0]
  11.  
  12.     N = len(x)
  13.  
  14.     z = np.zeros(N)
  15.     z[0] = c
  16.  
  17.  
  18.     for k in range(0,N-1):
  19.         k1 = f(z[k],x[k])
  20.  
  21.         k2 = f(z[k]+ ((H) * (k1/2)), x[k] + (H/2) )
  22.  
  23.         k3 = f(z[k]+ (H * (k2/2)), x[k] + (H/2) )
  24.  
  25.         k4 = f(z[k]+ (H * k3) , x[k] + H )
  26.  
  27.         z[k+1] =  z[k] + ((H/6) * (k1 + 2*k2 + 2*k3 + k4) )
  28.     return z
  29.        
  30. H = 0.01
  31. x =  np.arange(4,5,H)
  32.  
  33. z0 = -3
  34.  
  35. z_odeint =  odeint(f,z0,x)
  36.  
  37. z_rk_4 =  RK4OdeSys(f,z0,x)
  38.  
  39. z_actual = g(x)
  40. z_odeint = z_odeint.reshape(100,)
  41.  
  42. fig = plt.figure(1,figsize=(8,5))
  43. er1 = abs(z_actual - z_odeint)
  44. plt.plot(x,er1)
  45. er2 = abs(z_actual - z_rk_4)
  46. plt.plot(x,er2,"r")
  47. plt.xlabel("x")
  48. plt.ylabel("y")
  49. plt.legend(["exact vs odeint","Exact vs Rung-Kutta"])
  50. plt.title("Comparision of approximation errors")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement