问题描述
我想用 Python 编写一个程序,其中用户定义多项式和系数 (a,b,c) 的度数.当程序使用这些数据创建多项式表达式时,我想像函数一样使用它,因为我需要它来进行其他操作.我怎么才能得到它?例如,当我有 polynomial= x^n+a^n-1+b^n-2+c^-3 我想在 polynomial(x) 中使用它来计算值.
I'd like to write a program in Python where user define a deegre of polynomial and coefficients (a,b,c). When program create a polynomial expression with this data I'd like to use it like function because I need this to other operations. How can i get it? For example when I have polynomial= x^n+a^n-1+b^n-2+c^-3 I'd like to use it in polynomial(x) to calculate value.
现在创建多项式方法看起来:
Now the creating polynomial method looks:
def polynomial(n,a,b,c):
return a*x**n+b*x**3-c*x
推荐答案
class Polynomial:
def __init__(self, coeficents, degrees=None):
if degrees = None:
self.degree = list(reversed(range(len(coeficents))))
else:
self.degree = degrees
self.coeficents = coeficents
def __call__(self, x):
print(self.coeficents)
print(self.degree)
return sum([self.coeficents[i]*x**self.degree[i] for i in range(len(self.coeficents))])
p = Polynomial([1,2,4],[10,2,0])
print(p(2))
这将计算 x = 2
处的多项式 x^10 + 2x^2 + 4
.如何使用您的示例应该非常清楚.
This will compute the polynomial x^10 + 2x^2 + 4
at x = 2
. It should be very clear how to use with your example.
这篇关于如何在 Python 中创建类似函数的多项式表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!