I am trying to plot a function using the __call__
dunder for a custom class
import math
import numpy as np
import matplotlib.pyplot as plt
class F:
def __init__(self, n, m):
self._n = n
self._m = m
def __call__(self, x):
return math.sin(self._n * x) * math.cos(self._m * x)
u = F(1,1)
v = F(1,1)
x_array = np.linspace(0, 2*np.pi, 20)
u_array = u(x_array)
v_array = v(x_array)
plt.plot(u_array, v_array)
plt.show()
However, executing the code, i get this error
Traceback (most recent call last):
File "F.py", line 18, in <module>
u_array = u(x_array)
File "F.py", line 11, in __call__
return math.sin(self._n * x) * math.cos(self._m * x)
TypeError: only size-1 arrays can be converted to Python scalars
It seems that the call u_array = u(x_array)
sends the entire x_array to the function, instead of doing it in a vectorized way.
Please help
Use the numpy
vectorized functions instead of those from math
:
def __call__(self, x):
return np.sin(self._n * x) * np.cos(self._m * x)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.