File tree Expand file tree Collapse file tree 2 files changed +32
-0
lines changed Expand file tree Collapse file tree 2 files changed +32
-0
lines changed Original file line number Diff line number Diff line change @@ -291,6 +291,19 @@ def calculate(self, x):
291
291
292
292
return sum (ak * (x ** k ) for ak , k in self .terms )
293
293
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
+
294
307
def __call__ (self , x ):
295
308
"""Calculate the value of the polynomial at a given point."""
296
309
return self .calculate (x )
Original file line number Diff line number Diff line change @@ -1310,6 +1310,25 @@ def test_calculate_zero_polynomial(self):
1310
1310
self .assertEqual (0 , Constant (0 ).calculate (5 ))
1311
1311
self .assertEqual (0 , Monomial (0 , 1 ).calculate (1.1 ))
1312
1312
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
+
1313
1332
def test_call (self ):
1314
1333
"""Tests calculate on a simple polynomial."""
1315
1334
a = Polynomial (1 , 2 , 3 )
You can’t perform that action at this time.
0 commit comments