Skip to content

Commit

Permalink
Merge pull request #52 from Deric-W/master
Browse files Browse the repository at this point in the history
add Polynomial.calculate_horner
  • Loading branch information
yalishanda42 authored Dec 10, 2022
2 parents ac0a6fa + f6f53a1 commit 014f5e8
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
12 changes: 12 additions & 0 deletions polynomial/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,18 @@ def calculate(self, x):

return sum(ak * (x ** k) for ak, k in self.terms)

def calculate_horner(self, x):
"""Calculate the value of the polynomial at a given point.
This method is using Horner`s method and faster than calling
calculate for almost all polynomials except monomials but might
produce slightly different results when using floats.
"""
result = 0
for coeff in self:
result = coeff + x * result
return result

def __call__(self, x):
"""Calculate the value of the polynomial at a given point."""
return self.calculate(x)
Expand Down
19 changes: 19 additions & 0 deletions tests/test_polynomials_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -1310,6 +1310,25 @@ def test_calculate_zero_polynomial(self):
self.assertEqual(0, Constant(0).calculate(5))
self.assertEqual(0, Monomial(0, 1).calculate(1.1))

def test_calculate_horner(self):
"""Tests calculate_horner on a simple polynomial."""
a = Polynomial(1, 2, 3)

def eqn(x):
return x ** 2 + 2 * x + 3

for i in range(-100, 100):
i = i / 100
self.assertAlmostEqual(eqn(i), a.calculate_horner(i))

def test_calculate_horner_zero_polynomial(self):
"""Test that calculations of zero polynomial values
using Horner`s method always give 0.
"""
self.assertEqual(0, ZeroPolynomial().calculate_horner(1))
self.assertEqual(0, Constant(0).calculate_horner(5))
self.assertEqual(0, Monomial(0, 1).calculate_horner(1.1))

def test_call(self):
"""Tests calculate on a simple polynomial."""
a = Polynomial(1, 2, 3)
Expand Down

0 comments on commit 014f5e8

Please sign in to comment.