Search code examples
pythonnumpytypeerror

Function as argument raises TypeError ndarray


I have to analyse a mass with variable acceleration. The first function defines acceleration. The second return arrays for respectively place, speed and acceleration at time t. (t goes from 0-10 with increments of 0.1)

import numpy as np
import matplotlib.pyplot as plt

dt = 0.1
t0 = 0.0
t1 = 10.0
x0 = 0.0
v0 = 0.0
m = 5.0

t = np.linspace(0, 10, 101)

def versnelling(t):
    return (0.7 * np.sin(3 * t)) / m

def numeriek(x0, v0, a_func, t):
    x = np.zeros(len(t))
    v = np.zeros(len(t))
    a = np.zeros(len(t))
    x[0] = x0
    v[0] = v0
    a[0] = a_func(t[0])
    
    for i in range(len(t) - 1):
        dt = t[i + 1] - t[i]
        a[i + 1] = a0 + a_func(i)
        v[i + 1] = v[i] + a[i] * dt
        x[i + 1] = x[i] + v[i] * dt
        
    return x, v, a

But when I call it:

numeriek(x0, v0, versnelling(t), t)

I get:

TypeError: 'numpy.ndarray' object is not callable

I tried just a 0 in a_function(), as well as a t

How do I fix it but most of all why does my code not work??


Solution

  • The parameter a_func seems to be a function, so when you call the numeriek it should be passed as versnelling and not versnelling(t) that is in fact a function invocation resulting in a value.

    import numpy as np
    import matplotlib.pyplot as plt
    
    dt = 0.1
    t0 = 0.0
    t1 = 10.0
    x0 = 0.0
    v0 = 0.0
    m = 5.0
    
    t = np.linspace(0, 10, 101)
    
    
    def versnelling(t):
        return (0.7 * np.sin(3 * t)) / m
    
    
    def numeriek(x0, v0, a_func, t):
        x = np.zeros(len(t))
        v = np.zeros(len(t))
        a = np.zeros(len(t))
        x[0] = x0
        v[0] = v0
        a[0] = a_func(t[0])
        
        for i in range(len(t) - 1):
            dt = t[i + 1] - t[i]
            a[i + 1] = a[0] + a_func(i)
            v[i + 1] = v[i] + a[i] * dt
            x[i + 1] = x[i] + v[i] * dt
            
        return x, v, a
    
    
    if  __name__ == "__main__":
        print(numeriek(x0, v0, versnelling, t))