Arthur
Arthur

Reputation: 41

How to find exact roots in python (for cubics)

A program I'm writing involves solving many cubic polynomials. Upon using np.roots, it appears to me that for cubics, the roots are 'approximated roots'.

In [5]: np.roots([1,3,3,1])
Out[5]: array([-0.99999672+5.68937417e-06j, -0.99999672-5.68937417e-06j,
   -1.00000657+0.00000000e+00j])

So, the roots seem to be pretty close to being correct, in terms of the real parts being very close to -1, and the complex parts being very small, or nonexistent.

It is important for me that integer roots come out as integers, and not some real/complex number that 'closely resembles' it (roughly speaking).

Any input is appreciated, thank you in advance.

Upvotes: 2

Views: 4133

Answers (2)

hiro protagonist
hiro protagonist

Reputation: 46849

if you are willing to use sympy:

from sympy import var, Eq, solve

x = var('x')
sol = solve(Eq(x**3 + 3*x**2 + 3*x + 1, 0), x)
print(sol)  # output: [-1]

factor could also be used to verify the solution:

from sympy import factor
fact = factor(x**3 + 3*x**2 + 3*x + 1)
print(fact)  # (x + 1)**3

Upvotes: 2

Rory Daulton
Rory Daulton

Reputation: 22544

I'll assume that the coefficients of your cubic polynomials are integers, since that is true of your example.

I see at least two ways to do what you want. First, you can use np.roots as you have been. Then round each solution to the nearest (real) integer and plug that integer into the original polynomial--this can be done with exact precision. If the result of the polynomial is zero, use that integer rather than the returned root. If it would help, you could round to the nearest Gaussian integer and try that--that may be useful for your needs

Another way is for you to search for integral roots before using np.roots. You can use the Rational Root Theorem to search for those integer roots. This involves factoring the constant and leading coefficients. This method will also find rational but non-integral roots, which you may want. If the coefficients are large, finding the factors and/or trying all the possibilities may be time-consuming.

Upvotes: 1

Related Questions