2014-01-20 44 views
0
import numpy as np 
import matplotlib.pyplot as plt 

def inner(x,y): 
    result= 0 
    t  = np.size(x) 
    for i in range(1,t): 
     result += x[i]*y[i] 
    return result 

j = 1000 
dif = [None]*j 
for i in range(1,j): 
    t = 1000 
    x = np.random.rand(t) 
    y = np.random.rand(t) 
    dif[i] = np.inner(x,y)-inner(x,y) 

plt.plot(dif) 

dif[1:5] 
[0.33178257274579437, 
0.07784229846930657, 
0.027789489089741437, 
0.23682733988198379] 

我用np.inner和我自己寫的函數計算了兩個n * 1數組的內積。爲什麼有差異? np.inner vs inner

我預計這兩個應該是相同的。但事實證明,實際上有一些不平凡的差異。

這是爲什麼?我的代碼有什麼問題嗎?

回答

1

在您的inner()中,您從1重複爲t。你應該從0開始。

+0

該死!我知道python中的數組索引從0開始,當我真的在做這件事時就忘記了這一點。謝謝。 –