1
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

def f(x, t):       #function for 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
    for i 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 just trying to plot the Rk4 function for x0 = 1.0, t0 = 0.0 as a function of dt. I tried by vectorizing the function and creating an array for the timestep dt, but get the error "ValueError: setting an array element with a sequence."

hpaulj
  • 221,503
  • 14
  • 230
  • 353
infinitylord
  • 175
  • 7

1 Answers1

1

The problem is that your return value E is not a single number, but a numpy array.

Vectorizing many arrays would give you a list, vectorizing many numpy arrays does not work here.

To come back to your original question: The way to plot a function against one of its arguments using vectorization is:

from __future__ import division
import numpy as np
import matplotlib.pyplot as 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()

enter image description here

tfv
  • 6,016
  • 4
  • 36
  • 67