Evaluating polynomial using python -
i'm trying create own polynomial class. want make function can evaluate polynomial x given.
so far have this, answers giving me aren't right , cant figure out why? polynomials inputted using list. example [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 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 both index , exponent. you're evaluating reversed-coefficeint polynomial, evaluation results polynomial([2,3,4])
right value polynomial([4,3,2])
.
here's how i'd define evaluate
:
def evaluate(self, x): return sum(coef * x**exp exp, coef in enumerate(reversed(self.coeffs)))
note if want polynomial
objects callable (as in p1(4)
in example in comment), should rename evaluate
function __call__
.
Comments
Post a Comment