Alexis
Alexis

Reputation: 120

poly1d gives erroneous coefficients when they are very large integers

I am working with python 3.5.2 in ubuntu 16.04.2 LTS, and NumPy 1.12.1. When I use poly1d function to get the coeffs, there is a mistake with the computation:

>>> from numpy import poly1d
>>> from math import fabs
>>> pol = poly1d([2357888,459987,78123455],True)
>>>[int(x) for x in pol.coeffs]
[1, -80941330, 221226728585581, -84732529566356586496]

as you see in this list the last element is not correct. When I build the polynomial using Wolfram Alpha, I get:

x^3 - 80941330 x^2 + 221226728585581 x - 84732529566356580480

The last coefficient is different using poly1d (the first-one ends in ...496 and the other ends in ...480).Ii have to suppose that the correct ones is the last compute (made by WolframAlpha).

Is this a bug or is there something I am not taking account of? I've probed with roots with low absolute value; and in this case the computation is correct. But when I use "big roots", the difference is notable.

Upvotes: 3

Views: 934

Answers (2)

user6655984
user6655984

Reputation:

As Warren Weckesser said, this is a precision issue. But it can be worked around by declaring the array of roots to be of type object. In this way you can take advantage of Python's big integers, or of higher precision provided by mpmath objects. NumPy is considerate enough not to coerce them to double precision. Example:

import numpy as np
roots = np.array([2357888, 459987, 78123455], dtype=object)
pol = np.poly1d(roots, True)
print(pol.coeffs)

Output: [1 -80941330 221226728585581 -84732529566356580480]

Upvotes: 5

Warren Weckesser
Warren Weckesser

Reputation: 114781

The coefficients are stored as 64 bit floating point values. These do not have enough precision to represent the value -84732529566356580480 exactly.

Upvotes: 3

Related Questions