Skip to content

Commit 49317cd

Browse files
committed
add Polynomial.calculate_horner
This allows to evaluate polynomials more efficiently.
1 parent 4982347 commit 49317cd

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

polynomial/core.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,19 @@ def calculate(self, x):
291291

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

294+
def calculate_horner(self, x):
295+
"""Calculate the value of the polynomial at a given point
296+
using Horner`s method.
297+
298+
This method is faster than calling calculate for almost all
299+
polynomials except monomials but might produce slightly different
300+
results when using floats.
301+
"""
302+
result = 0
303+
for coeff in self:
304+
result = coeff + x * result
305+
return result
306+
294307
def __call__(self, x):
295308
"""Calculate the value of the polynomial at a given point."""
296309
return self.calculate(x)

tests/test_polynomials_operations.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1310,6 +1310,25 @@ def test_calculate_zero_polynomial(self):
13101310
self.assertEqual(0, Constant(0).calculate(5))
13111311
self.assertEqual(0, Monomial(0, 1).calculate(1.1))
13121312

1313+
def test_calculate_horner(self):
1314+
"""Tests calculate_horner on a simple polynomial."""
1315+
a = Polynomial(1, 2, 3)
1316+
1317+
def eqn(x):
1318+
return x ** 2 + 2 * x + 3
1319+
1320+
for i in range(-100, 100):
1321+
i = i / 100
1322+
self.assertAlmostEqual(eqn(i), a.calculate_horner(i))
1323+
1324+
def test_calculate_horner_zero_polynomial(self):
1325+
"""Test that calculations of zero polynomial values
1326+
using Horner`s method always give 0.
1327+
"""
1328+
self.assertEqual(0, ZeroPolynomial().calculate_horner(1))
1329+
self.assertEqual(0, Constant(0).calculate_horner(5))
1330+
self.assertEqual(0, Monomial(0, 1).calculate_horner(1.1))
1331+
13131332
def test_call(self):
13141333
"""Tests calculate on a simple polynomial."""
13151334
a = Polynomial(1, 2, 3)

0 commit comments

Comments
 (0)