2017-02-25 30 views
0

我想用matplotlib呈现一个6度函数,它与我找到的这段代码一起工作,但不能和python3一起工作。matplotlib在python3中失败

import numpy as np 
from matplotlib import pyplot as plt 

def langrange_polynomial(X, Y): 
    def L(i): 
     return lambda x: np.prod([(x-X[j])/(X[i]-X[j]) for j in range(len(X)) if i != j]) * Y[i] 
    Sx = [L(i) for i in range(len(X))] # summands 
    return lambda x: np.sum([s(x) for s in Sx]) 

# cut something 

# Here i get the points with a function 
(X, Y) = [1,2,3,4,5,6,7],[0,20,10,4,3,40,4] 
F = langrange_polynomial(X, Y) 

x_range = np.linspace(X[0], X[-1], 100) 
plt.plot(X, Y, 'ro') 
plt.plot(x_range, map(F, x_range)) 
plt.xlabel(r'$x$') 
plt.ylabel(r'$F(x)$') 
plt.title('Lagrange polynomial interpolation') 
plt.grid(True) 
plt.show() 

得到这个错误:

raise ValueError("x and y must have same first dimension") 
ValueError: x and y must have same first dimension 

在该行:

plt.plot(x_range, map(F, x_range)) 

我读到一些有关声明X,Y坐标到np.array,但没有反正工作。我在Python3.5中必须做什么?

回答

1

在python 3中,map(function, iterable)返回一个迭代器而不是一个列表。
您需要通过

list(map(function, iterable)) 

得到一个列表,或者更具体地说是在这种情况下

plt.plot(x_range, list(map(F, x_range))) 
+0

从来没有想到,;-)非常感谢! –

相关问题