Skip to content

Commit 4982347

Browse files
committed
Add __call__
1 parent b2132f8 commit 4982347

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,9 @@ Polynomial(12, 6, 2)
5555
``` pycon
5656
>>> (a + b).calculate(5)
5757
780
58+
59+
>>> а(2) # equivalent to a.calculate(2)
60+
26
5861
```
5962

6063
### Multiplication

polynomial/core.py

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

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

294+
def __call__(self, x):
295+
"""Calculate the value of the polynomial at a given point."""
296+
return self.calculate(x)
297+
294298
def __getattr__(self, name):
295299
"""Get coefficient by letter name: ax^n + bx^{n-1} + ... + yx + z."""
296300
if len(name) != 1:

tests/test_polynomials_operations.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1310,6 +1310,23 @@ 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_call(self):
1314+
"""Tests calculate 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.assertEqual(eqn(i), a(i))
1323+
1324+
def test_call_zero_polynomial(self):
1325+
"""Test that calculations of zero polynomial values always give 0."""
1326+
self.assertEqual(0, ZeroPolynomial()(1))
1327+
self.assertEqual(0, Constant(0)(5))
1328+
self.assertEqual(0, Monomial(0, 1)(1.1))
1329+
13131330
def test_setattr_raises_error(self):
13141331
"""Test that setting invalid terms raises an error."""
13151332
invalid_setattrs = [

0 commit comments

Comments
 (0)