简体   繁体   English

使用python评估多项式

[英]Evaluating polynomial using python

I'm trying to create my own polynomial class. 我正在尝试创建自己的多项式类。 I want to make a function that can evaluate a polynomial where x is given. 我想做一个可以评估给出x的多项式的函数。

So far I have this, however the answers its giving me aren't right and I cant figure out why? 到目前为止,我已经知道了,但是它给我的答案是不正确的,我不知道为什么? The polynomials are inputted using a list. 使用列表输入多项式。 For example [2, 0, 1, -7, 13] would be 2x^4+x^2-7x+13 例如[2,0,1,-7,13]将是2x ^ 4 + x ^ 2-7x + 13

class Polynomial:

def __init__(self, coefficients):
    self.coeffs=coefficients

def evaluate(self, x):
    sum = 0
    for i in range(len(self.coeffs)-1,0,-1):
        sum+=self.coeffs[i]*(x**i)
    return sum

The i value you're using isn't right for both the index and the exponent. 您使用的i值对索引和指数均不正确。 You're actually evaluating the reversed-coefficeint polynomial, so your evaluation results for Polynomial([2,3,4]) are actually the right value for Polynomial([4,3,2]) . 您实际上是在评估逆系数系数多项式,因此对Polynomial([2,3,4])评估结果实际上是对Polynomial([4,3,2])的正确值。

Here's how I'd define evaluate : 这是我定义evaluate

def evaluate(self, x):
    return sum(coef * x**exp for exp, coef in enumerate(reversed(self.coeffs)))

Note that if you want your Polynomial objects to be callable (as in p1(4) in the example in your comment), you should rename your evaluate function __call__ . 请注意,如果希望Polynomial对象可调用(如注释示例中的p1(4)所示),则应重命名evaluate函数__call__

There is an error expected an indented block for this code. 预期该代码的缩进块存在错误。 To resole the error, be sure to include an indentation block: 要重现错误,请确保包括缩进块:

class Polynomial:
    def __init__(self, coefficients):
        self.coeffs=coefficients

    def _call_(self, x):
    return sum(coef * x**exp for exp, coef in enumerate(reversed(self.coeffs)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM