對于這樣的常規功能
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
從其他帖子中,我知道__call__通過某些np.函式對方法進行矢量化是可行的,但是例如,f上面的函式也不是矢量化的,并且在兩種型別的輸入中都可以正常作業。可以使此類__call__方法接受兩種引數型別(浮點數和浮點數陣列)嗎?
uj5u.com熱心網友回復:
修復:沒有型別檢查。
由于np.array可以同時接受np.array 和標量的輸入,我們可以創建一個新np.array的 int 型別
ind = np.array(t * (self.n_sections/self.T), dtype=int)
測驗用例:
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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/496215.html
上一篇:在另一個類中使用一個類的屬性
下一篇:無法列印類中的物件
