pythonnumpynumpy-ndarray

Declaring a new math function using NumPy


A simple issue:

Why does

import numpy as np
f = np.sin(x)
print(f(0.3))

return an error; whereas

import numpy as np
print(np.sin(0.3))

does not?

Suppose, for instance I wanted to store f as:

f(x) = sin(x) + 2*sin(3.4*x)

How would I go about this?


Solution

  • You need a lambda function, if I understand your uses correctly:

    f = lambda x: np.sin(x) + np.sin(3.456 * x)
    print(f(0.3))
    

    Some more details on lambda can be found here.