Runge-Kutta 4 with 3 variable equation

  math, numerical-methods, python

I’m trying to implement a RK4 for a equation that is given by

x'(t)=0.4x(t)-0.018x(t)y(t); x(0)=30

y'(t)=-0.8y(t)+0.023x(t)y(t); y(0)=4

and i got this code


def f(x,y,t):
    return 0.4*x*t-0.018*x*t*y


def rk4(x0,y0,xn,n):
    

    h = (xn-x0)/n
    
    print('n--------SOLUTION--------')
    print('-------------------------')    
    print('x0ty0tyn')
    print('-------------------------')
    for i in range(n):
        k1 = h * (f(x0, y0))
        k2 = h * (f((x0+h/2), (y0+k1/2)))
        k3 = h * (f((x0+h/2), (y0+k2/2)))
        k4 = h * (f((x0+h), (y0+k3)))
        k = (k1+2*k2+2*k3+k4)/6
        yn = y0 + k
        print('%.4ft%.4ft%.4f'% (x0,y0,yn) )
        print('-------------------------')
        y0 = yn
        x0 = x0+h
    
    print('nAt x=%.4f, y=%.4f' %(xn,yn))


print('Enter initial conditions:')
x0 = float(input('x0 = '))
y0 = float(input('y0 = '))

print('Enter calculation point: ')
xn = float(input('xn = '))

print('Enter number of steps:')
step = int(input('Number of steps = '))


rk4(x0,y0,xn,step)

the problem is that i dont know how to use the t variable

Source: Python Questions

LEAVE A COMMENT