0% found this document useful (0 votes)
4 views2 pages

Numerical Methods for ODEs in Python

The document shows code for numerically solving differential equations using the Runge-Kutta method of order 4. It imports NumPy and matplotlib, defines functions for the differential equation and Runge-Kutta steps, runs the simulation, and plots the results.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Numerical Methods for ODEs in Python

The document shows code for numerically solving differential equations using the Runge-Kutta method of order 4. It imports NumPy and matplotlib, defines functions for the differential equation and Runge-Kutta steps, runs the simulation, and plots the results.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

import numpy as np

import [Link] as plt

n = 120
h = 0.25
def f(x,y):
dy = (0.2-2*10**(-6)*y)*y
return dy

y=[]
x=[]
[Link](1000)
[Link](0)

for k in range(0,n):
F1 = f(x[k],y[k])
F2 = f(x[k]+h/2,y[k]+h*F1/2)
F3 = f(x[k]+h/2,y[k]+h*F2/2)
F4 = f(x[k]+h,y[k]+h*F3)

[Link](x[k]+h)
[Link](y[k]+h*(F1+2*F2+2*F3+F4)/6)

for k in range(0,n+1):
print("%12.2f & %12.12f \n"%(x[k],y[k]) )

fig = [Link](figsize=(10, 8))


ax = fig.add_subplot(111)

[Link](x,y)
[Link]('graph_rk4.png')
import numpy as np

import [Link] as plt

from matplotlib import style

[Link]('ggplot')

% matplotlib inline

% config Inlinebackend.figure_format='svg'

def dydx(x, y):

return -20*y+20*x+21

n= 10

x0= 0

xf= 1

y0= 0.6

h= (xf-x0)/n

x=[x0]

y=[y0]

for i in range(n):

y0=y0 + h*dydx(x0, y0)

[Link](y0)

x0=x0 + h # x0 +=h

[Link](x0)

print(x)

print(y)

You might also like