0

I want to render a 6th degree function with matplotlib, it works with this code i found, but not with 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()

Get this Error:

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

in that Line:

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

I read about something about declare the X,Y Coordinates to an np.array, but that did not worked anyway. What do I have to do in Python3.5?

1 Answer 1

1

In python 3, map(function, iterable) returns an iterator instead of a list.
You would need to get a list via

list(map(function, iterable))

or, more specifically in this case

plt.plot(x_range, list(map(F, x_range)))
Sign up to request clarification or add additional context in comments.

1 Comment

would have never guessed that ;-) Thanks alot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.