Solving An Ode Y'=f (x) With Numerical Values Of F (x) But Without Analitical Expresion
I want to solve an ODE numerically in python, like y'=f(x) (with boundary condition y(0)=0). I don't know what the analytical expression of function f(x), instead I have a set of p
Solution 1:
You should be able to solve this using the quadrature routines of scipy.integrate
. If you really want to use the complicated form, you have to use interpolation, for instance as in
from scipy.integrate import odeint
from scipy.interpolate import interp1d
import numpy as np
xs = np.linspace(0,10,100+1);
fs = np.sin(xs)*np.exp(-0.1*xs) # = Imag( exp((1j-0.1)*x) )# the exact anti-derivative of f is # F = Imag( (exp((1j-0.1)*x)-1)/(1j-0.1) )# = Imag( -(1j+0.1)*(exp((1j-0.1)*x)-1)/(1.01) )# = 1/1.01 - exp(-0.1*x)/1.01 * ( cos(x) + 0.1*sin(x) )defIntF(x): return (1-np.exp(-0.1*x)*(np.cos(x)+0.1*np.sin(x)))/1.01
f = interp1d(xs, fs, kind="quadratic", fill_value="extrapolate")
defdy_dx(y, x):
return f(x)
ys = odeint(dy_dx, 0.0, xs)
for x,y inzip(xs, ys): print"%8.4f %20.15f %20.15f"%(x,y,IntF(x))
with the first 10 lines
x interpolated exact
--------------------------------------------------0.00000.0000000000000000.0000000000000000.10000.0049654204704930.0049626592389910.20000.0196719885002990.0196698011886310.30000.0437837300813580.0437815293360000.40000.0768727887804230.0768707139372780.50000.1184309932426310.1184289869142740.60000.1678753572401000.1678734297170740.70000.2245557186423100.2245538736110320.80000.2877624898704170.2877607273222300.90000.3567349396069630.3567332433910021.00000.4306697602361510.430668131955269
Post a Comment for "Solving An Ode Y'=f (x) With Numerical Values Of F (x) But Without Analitical Expresion"