Skip to content

Commit 014f5e8

Browse files
authored
Merge pull request #52 from Deric-W/master
add Polynomial.calculate_horner
2 parents ac0a6fa + f6f53a1 commit 014f5e8

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

polynomial/core.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,18 @@ 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+
297+
This method is using Horner`s method and faster than calling
298+
calculate for almost all polynomials except monomials but might
299+
produce slightly different results when using floats.
300+
"""
301+
result = 0
302+
for coeff in self:
303+
result = coeff + x * result
304+
return result
305+
294306
def __call__(self, x):
295307
"""Calculate the value of the polynomial at a given point."""
296308
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)