对于像这样的常规函数
def f(t):
return t*t
我可以传递两个值或NumPy数组没有问题。例如:
T = 1
print(f(T))
times = np.mgrid[0 : T : 100j]
values = f(times)
现在我用__call__
函数创建了一个类
class rnd_elemental_integrand:
def __init__(self, n_sections, T):
self.n_sections = n_sections
self.T = T
self.generate()
def generate(self):
self.values = norm.rvs(size = (self.n_sections + 1,), scale = 1)
def __call__(self, t):
ind = int(t * (self.n_sections/self.T))
return self.values[ind]
但是对于这个类方法,我可以而不是传递一个NumPy数组。例如这个T = 5
elem_int_sections = 10
rnd_elem = rnd_elemental_integrand(elem_int_sections, T)
print(rnd_elem(T))
times = np.mgrid[0 : T : 100j]
values = rnd_elem(times)
产生输出
0.43978851468955377
Traceback (most recent call last):
File "/Users/gnthr/Desktop/Programming/Python/StochAna/stochana.py", line 138, in <module>
values = rnd_elem(times)
File "/Users/gnthr/Desktop/Programming/Python/StochAna/stochana.py", line 117, in __call__
ind = int(t * (self.n_sections/self.T))
TypeError: only size-1 arrays can be converted to Python scalars
从其他帖子中,我知道通过一些np.
函数对__call__
方法进行矢量化可以工作,但是例如,上面的函数f
也没有矢量化,并且可以很好地处理两种类型的输入。这个类__call__
方法可以接受两种参数类型(浮点数&数组的浮点数)?
修复:没有类型检查
由于np.array
可以同时接受np.array
和标量的输入,因此可以创建一个新的np.array
,类型为int
ind = np.array(t * (self.n_sections/self.T), dtype=int)
Testcase:
from scipy.stats import norm
T = 5
elem_int_sections = 10
rnd_elem = rnd_elemental_integrand(elem_int_sections, T)
print(rnd_elem(T))
times = np.mgrid[0 : T : 100j]
print (rnd_elem(times))
输出:
-0.7828585207846585
[-1.00037782 -1.00037782 -1.00037782 -1.00037782 -1.00037782 -1.00037782
-1.00037782 -1.00037782 -1.00037782 -1.00037782 1.35744571 1.35744571
1.35744571 1.35744571 1.35744571 1.35744571 1.35744571 1.35744571
1.35744571 1.35744571 0.65442428 0.65442428 0.65442428 0.65442428
0.65442428 0.65442428 0.65442428 0.65442428 0.65442428 0.65442428
0.76685108 0.76685108 0.76685108 0.76685108 0.76685108 0.76685108
0.76685108 0.76685108 0.76685108 0.76685108 0.48888641 0.48888641
0.48888641 0.48888641 0.48888641 0.48888641 0.48888641 0.48888641
0.48888641 0.48888641 0.62681856 0.62681856 0.62681856 0.62681856
0.62681856 0.62681856 0.62681856 0.62681856 0.62681856 0.62681856
1.05695641 1.05695641 1.05695641 1.05695641 1.05695641 1.05695641
1.05695641 1.05695641 1.05695641 1.05695641 -0.0634099 -0.0634099
-0.0634099 -0.0634099 -0.0634099 -0.0634099 -0.0634099 -0.0634099
-0.0634099 -0.0634099 -0.00167191 -0.00167191 -0.00167191 -0.00167191
-0.00167191 -0.00167191 -0.00167191 -0.00167191 -0.00167191 -0.00167191
1.16756173 1.16756173 1.16756173 1.16756173 1.16756173 1.16756173
1.16756173 1.16756173 1.16756173 -0.78285852]