简体   繁体   English

Python 类 __call__ 函数未矢量化

[英]Python class __call__ function is not vectorized

I am trying to plot a function using the __call__ dunder for a custom class我正在尝试使用__call__ dunder 为自定义类绘制函数

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.似乎调用u_array = u(x_array)将整个 x_array 发送到函数,而不是以矢量化的方式进行。

Please help请帮忙

Use the numpy vectorized functions instead of those from math :使用numpy向量化函数而不是来自math函数:

def __call__(self, x):
    return np.sin(self._n * x) * np.cos(self._m * x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM