Isak Baizley
Isak Baizley

Reputation: 1843

IPython, Plotting a Polynomial

I've been working with Sympy for an Interpolation, in which I obtain as a result a 7th degree Polynomial (ax^7 + bx^6 + cx^5 + ...+ h) which I want to Plot, but wen I try to plot it I get errors, for example, if I try:

plt.plot(r,U.subs(x,r))

where r = np.linspace(0,20,num=100) and U = Polynomial(x); the result is an error message: ValueError: sequence too large; must be smaller than 32, I obtain MemoryError: if I try `r = np.arange(20)'. The only way I could plot it is with a for cycle, substituting one by one and saving it in another variable as a list. So my question is, what is wrong with the first's inputs? is there an easy way to plot a polynomial?

Upvotes: 1

Views: 506

Answers (1)

Dietrich
Dietrich

Reputation: 5531

Welcome to SO!

The subs() method is not meant to be used with numpy arrays. lambdify() does what you want. Try:

import numpy as np
import matplotlib.pyplot as plt
import sympy as sy

sy.init_printing()  # nice formula rendering in IPython

x = sy.symbols("x", real=True)

# the sample polynomial:
pp = x**3  + 3*x**2 - 6*x - 8 

# Convert expression function usable with numpy array:
f_pp = sy.lambdify(x, pp, modules=np)

# Do the plotting:
x_n = np.linspace(-5, 2, 500)
y_n = f_pp(x_n)  # evaluate all x_n

fg, ax = plt.subplots(1, 1)
ax.plot(x_n, y_n)
fg.canvas.draw()
plt.show()

The parameter modules=np ensures, that numpy is used for functions in the expression (e.g., sin() => np.sin()). In this example, it is not explicitly needed.

PS: If you include a runnable example in your question, it makes live much easier for potential answerers.

Upvotes: 2

Related Questions