I am trying to solve a third order non linear differential equation. I have tried to transform it and I've obtained this problem which is a second order problem:
I am trying to implement a fourth order Range-Kutta algorithm in order to solve it by writing it like this :
Here is my code for the Range-Kutta algorithm :
import numpy as np
import matplotlib.pyplot as plt
''''X,Y = integrate(F,x,y,xStop,h).
4th-order Runge-Kutta method for solving the initial value problem {y}' = {F(x,{y})}, where {y} = {y[0],y[1],...,y[n-1]}.
x,y = initial conditions
xStop = terminal value of x
h = increment of x used in integration
F = user-supplied function that returns the
array F(x,y) = {y'[0],y'[1],...,y'[n-1]}.
'''
def integrate(F,x,y,xStop,h):
def run_kut4(F,x,y,h):
K0 = h*F(x,y)
K1 = h*F(x + h/2.0, y + K0/2.0)
K2 = h*F(x + h/2.0, y + K1/2.0)
K3 = h*F(x + h, y + K2)
return (K0 + 2.0*K1 + 2.0*K2 + K3)/6.0
X =[]
Y =[]
X.append(x)
Y.append(y)
while x < xStop:
h = min(h,xStop - x)
y = y + run_kut4(F,x,y,h)
x = x + h
X.append(x)
Y.append(y)
return np.array(X),np.array(Y)
It works fine for other differential equations.
In this case the function F is defined as :
And the main code is :
def F(x,y):
F = np.zeros(2)
F[0] = y[1]
F[1] = (2*(1-x)/x**3)*y[0]**(-1/2)
return F
x = 1.0
xStop = 20
y = np.array([0,0])
h = 0.2
X,Y = integrate(F,x,y,xStop,h)
plt.plot(X,Y)
plt.grid()
plt.show()
Unfortunately, I got this error :
<ipython-input-8-8216949e6888>:4: RuntimeWarning: divide by zero encountered in power
F[1] = (2*(1-x)/x**3)*y[0]**(-1/2)
<ipython-input-8-8216949e6888>:4: RuntimeWarning: divide by zero encountered in double_scalars
F[1] = (2*(1-x)/x**3)*y[0]**(-1/2)
It's related to the fact that the initial value of the function is 0 but I don't know how to get rid of it in order to simplify the problem again...
Could someone help me to find an other alternative ?
Thank you for your help,
you
y
is[0,0]
and iny[0]**(-1/2)
there is division operation with0
in the denominator which is giving ZeroDivision warning and invalid value encountered in double_scalars is due to expressiony[0]**(-1/2)
changed toNaN
. however, those are warnings andF
is returning valuearray([ 0., nan])
. you need to replacey[0]**(-1/2)
as negative powers of zero are undefined or you can use an extremely small value near zero if it suits your need. maybe your equation is not continuous at (1,0).