我的代码是:
import numpy as np
import matplotlib as plt
polyCoeffiecients = [1,2,3,4,5]
plt.plot(PolyCoeffiecients)
plt.show()
这样的结果是描述1,2,3,4,5中的点和它们之间的直线的直线,而不是具有1,2,3,4,5的5的多项式。其系数(P(x)= 1 + 2x + 3x + 4x + 5x)
我怎么想用一个只用系数绘制多项式?
答案 0 :(得分:4)
Eyzuky,看看这是不是你想要的:
import numpy as np
from matplotlib import pyplot as plt
def PolyCoefficients(x, coeffs):
""" Returns a polynomial for ``x`` values for the ``coeffs`` provided.
The coefficients must be in ascending order (``x**0`` to ``x**o``).
"""
o = len(coeffs)
print(f'# This is a polynomial of order {ord}.')
y = 0
for i in range(o):
y += coeffs[i]*x**i
return y
x = np.linspace(0, 9, 10)
coeffs = [1, 2, 3, 4, 5]
plt.plot(x, PolyCoefficients(x, coeffs))
plt.show()
答案 1 :(得分:2)
一个非常Python的解决方案是使用列表推导来计算该函数的值。
import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(0, 10, 11)
coeffs = [1, 2, 3, 4, 5]
y = np.array([np.sum(np.array([coeffs[i]*(j**i) for i in range(len(coeffs))])) for j in x])
plt.plot(x, y)
plt.show()
答案 2 :(得分:2)
您可以通过获取许多x值并使用np.polyval()
来在x值处获取多项式的y值来近似绘制多项式。然后,您只需绘制x值和y值即可。
import numpy as np
import matplotlib.pyplot as plt
curve = np.array([1,2,3,4,5])
x = np.linspace(0,10,100)
y = [np.polyval(curve, i) for i in x]
plt.plot(x,y)
答案 3 :(得分:1)
通用的矢量化实现:
from typing import Sequence, Union
import numpy as np
import matplotlib.pyplot as plt
Number = Union[int, float, complex]
def polyval(coefficients: Sequence[Number], x: Sequence[Number]) -> np.ndarray:
# expand dimensions to allow broadcasting (constant time + inexpensive)
# axis=-1 allows for arbitrarily shaped x
x = np.expand_dims(x, axis=-1)
powers = x ** np.arange(len(coefficients))
return powers @ coefficients
def polyplot(coefficients: Sequence[Number], x: Sequence[Number]) -> None:
y = polyval(coefficients, x)
plt.plot(x, y)
polyplot(np.array([0, 0, -1]), np.linspace(-10, 10, 210))
plt.show()