0

Hey guys I'm receiving an error and I'm not 100% sure why it's happening. I'm trying to perform both the eulers and heun's methods and plot them against one another. Any help or suggestions would be awesome! I'm pretty novice with python so this is a bit new to me.

import numpy
#eulers 
yi = 0
h = 0.2
te = [0.0,2.0,0.2]
def euler(f, y0, t):
    n = len(t)
    y = numpy.array([y0] * n)
    for i in range(n - 1):
        y[i+1] = y[i] + (t[i+1] - t[i]) * f(y[i], t[i])
    return y
fy = (y*t**3) - 1.5*y
y1 = euler(fy, yi, te)

#heun
def heun(f, y0, t):
    n = len(t)
    y = numpy.array( [y0] * n )
    for i in range(n - 1):
        h = t[i+1] - t[i]
        k1 = h * f( y[i], t[i])
        k2 = h * f( y[i] + k1, t[i+1])
        y[i+1] = y[i] + (k1 + k2) / 2.0
    return y

y2 = heun(fy, 1, te)

tp = numpy.linspace(0.0, 2.0, 0.2)
plt.plot(tp, y1,'r-',linewidth=2,label='Eulers')
plt.plot(tp, y2,'b--',linewidth=2,label='Heun')
plt.xlabel('time')
plt.ylabel('y(t)')
plt.legend()
plt.show()

This is my error code:

TypeError                                 Traceback (most recent call last)
<ipython-input-152-395afeefc50a> in <module>()
     11     return y
     12 fy = (y*t**3) - 1.5*y
---> 13 y1 = euler(fy, yi, te)
     14 
     15 #heun

<ipython-input-152-395afeefc50a> in euler(f, y0, t)
      8     y = numpy.array([y0] * n)
      9     for i in range(n - 1):
---> 10         y[i+1] = y[i] + (t[i+1] - t[i]) * f(y[i], t[i])
     11     return y
     12 fy = (y*t**3) - 1.5*y

TypeError: 'numpy.ndarray' object is not callable
2
  • t is not defined... y is not defined... Where did you copy/paste this from? Commented Dec 1, 2017 at 4:39
  • If someone ran your code as you've shown, they would get a different error from you. It would fail on the line that defines fy because of the issues mentioned in the previous comment. It looks like you're using python interactively. Make sure when you post code that your code would run (or not run) as you expect in a brand new python session. Commented Dec 1, 2017 at 4:45

1 Answer 1

2

My guess is that you're trying to define a function f(y,t) in the line

fy = (y*t**3) - 1.5*y

as your differential equation. However, that is not how you define a function in python.

Try

def f(y,t): return y*t**3 - 1.5*y

You are getting an error because on line ---> 10 y[i+1] = y[i] + (t[i+1] - t[i]) * f(y[i], t[i])

f is a NumPy array, but you are treating it as a function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.