numpy - How to plot a defined function against one of its arguments in Python -
from __future__ import division import numpy np import matplotlib.pyplot plt def f(x, t): #function x'(t) = f(x,t) return -x def exact(t): #exact solution return np.exp(-t) def rk4(x0, t0, dt): #runge-kutta fourth order approximation t = np.arange(0, 1+dt, dt) n = len(t) x = np.array([x0]*n) e = np.array([x0]*n) e0 = x0-exact(1) x[0],t[0],e[0] = x0,t0,e0 in range(n-1): h = t[i+1] - t[i] k1 = h*f(x[i], t[i]) k2 = h*f(x[i] + 0.5 * k1, t[i] + 0.5 * h) k3 = h*f(x[i] + 0.5 * k2, t[i] + 0.5 * h) k4 = h*f(x[i] + k3, t[i+1]) x[i+1] = x[i] + (k1 + 2.0*(k2 + k3) + k4 )/6.0 e[i+1] = e[i]+(x[i+1]-x[i]) return e vecrk4 = np.vectorize(rk4) dtime = np.arange(10e-4,1,10e-5) s = vecrk4(1.0,0.0,dtime) plt.plot(dtime,s)
i'm trying plot rk4 function x0 = 1.0, t0 = 0.0 function of dt. tried vectorizing function , creating array timestep dt, error "valueerror: setting array element sequence."
the problem return value e
not single number, numpy array.
vectorizing many arrays give list, vectorizing many numpy arrays not work here.
to come original question: way plot function against 1 of arguments using vectorization is:
from __future__ import division import numpy np import matplotlib.pyplot plt def myfunc(a,b): return 2*b+a vecrk4 = np.vectorize(myfunc) dtime = np.arange(10e-4,1,10e-5) s = vecrk4(a=3, b=dtime) plt.plot(dtime,s) plt.show()
Comments
Post a Comment