cs_question_asker
cs_question_asker

Reputation: 87

How to plot curve with given polynomial coefficients?

using Python I have an array with coefficients from a polynomial, let's say

polynomial = [1,2,3,4]

which means the equation: y = 4x³ + 3x² + 2x + 1 (so the array is in reversed order)

Now how do I plot this into a visual curve in the Jupyter Notebook? There was a similar question: Plotting polynomial with given coefficients but I didn't understand the answer (like what is a and b?).

And what do I need to import to make this happen?

Upvotes: 3

Views: 3132

Answers (1)

pho
pho

Reputation: 25489

First, you have to decide the limits for x in your plot. Let's say x goes from -2 to 2. Let's also ask for a hundred points on our curve (this can be any sufficiently large number for your interval so that you get a smooth-looking curve)

Let's create that array:

lower_limit = -2
upper_limit = 2
num_pts = 100
x = np.linspace(lower_limit, upper_limit, num_pts)

Now, let's evaluate y at each of these points. Numpy has a handy polyval() that'll do this for us. Remember that it wants the coefficients ordered by highest exponent to lowest, so you'll have to reverse the polynomial list

poly_coefs = polynomial[::-1] # [4, 3, 2, 1]
y = np.polyval(poly_coefs, x)

Finally, let's plot everything:

plt.plot(x, y, '-r')

enter image description here

You'll need the following imports:

import numpy as np
from matplotlib import pyplot as plt

If you don't want to import numpy, you can also write vanilla python methods to do the same thing:

def linspace(start, end, num_pts):
    step = (end - start) / (num_pts - 1)
    return [start + step * i for i in range(num_pts)]

def polyval(coefs, xvals):
    yvals = []
    for x in xvals:
        y = 0
        for power, c in enumerate(reversed(coefs)):
            y += c * (x ** power)
        yvals.append(y)
    return yvals

Upvotes: 5

Related Questions