[英]How to plot curve with given polynomial coefficients?
using Python I have an array with coefficients from a polynomial, let's say使用 Python 我有一个包含多项式系数的数组,比方说
polynomial = [1,2,3,4]
which means the equation: y = 4x³ + 3x² + 2x + 1 (so the array is in reversed order)这意味着等式: y = 4x³ + 3x² + 2x + 1 (所以数组是相反的顺序)
Now how do I plot this into a visual curve in the Jupyter Notebook?现在我如何在 Jupyter Notebook 中把 plot 这个变成可视曲线? There was a similar question: Plotting polynomial with given coefficients but I didn't understand the answer (like what is a and b?).
有一个类似的问题: Plotting polynomial with given coefficients但我不明白答案(比如什么是 a 和 b?)。
And what do I need to import to make this happen?我需要导入什么来实现这一点?
First, you have to decide the limits for x
in your plot.首先,您必须确定 plot 中
x
的限制。 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)假设
x
从 -2 变为 2。我们还要求曲线上的一百个点(对于您的区间来说,这可以是任何足够大的数字,以便您获得看起来平滑的曲线)
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.现在,让我们在每个点上评估
y
。 Numpy has a handy polyval()
that'll do this for us. Numpy 有一个方便的
polyval()
可以为我们做这件事。 Remember that it wants the coefficients ordered by highest exponent to lowest, so you'll have to reverse the polynomial
list请记住,它希望系数按最高指数排序到最低,因此您必须反转
polynomial
列表
poly_coefs = polynomial[::-1] # [4, 3, 2, 1]
y = np.polyval(poly_coefs, x)
Finally, let's plot everything:最后,让我们 plot 一切:
plt.plot(x, y, '-r')
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:如果你不想导入
numpy
,你也可以编写 vanilla python 方法来做同样的事情:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.