1

Can I get trigonometric symbolic solution of cubic equation using Python/Sympy?

http://en.wikipedia.org/wiki/Casus_irreducibilis http://en.wikipedia.org/wiki/Cubic_function#Trigonometric_.28and_hyperbolic.29_method

denfromufa
  • 5,610
  • 13
  • 81
  • 138

1 Answers1

3

update: the solution given below is now available by using the keyword trig=True with roots or roots_cubic when solving such an equation.

This form is not given with any keyword I know of, but it is not hard to write a routine to do this:

>>> def cutrig(a,b,c,d):
...     a,b,c,d = [S(i) for i in (a,b,c,d)]
...     # x = t - b/3/a
...     p = (3*a*c-b**2)/3/a**2
...     q = (2*b**3-9*a*b*c+27*a**2*d)/(27*a**3)
...     D = 18*a*b*c*d-4*b**3*d+b**2*c**2-4*a*c**3-27*a**2*d**2
...     assert D > 0
...     rv = []
...     for k in range(3):
...         rv.append(2*sqrt(-p/3)*cos(acos(3*q/2/p*sqrt(-3/p))/3-k*2*pi/3))
...     return list(sorted([i - b/3/a for i in rv]))
...
>>> print filldedent(cutrig(-1,2,3,-2))

[-2*sqrt(13)*cos(-acos(8*sqrt(13)/169)/3 + pi/3)/3 + 2/3,
-2*sqrt(13)*sin(-acos(8*sqrt(13)/169)/3 + pi/6)/3 + 2/3, 2/3 +
2*sqrt(13)*cos(acos(8*sqrt(13)/169)/3)/3]
>>> 

Compared to the default solve solution:

>>> print filldedent(solve(-x**3+2*x**2+3*x-2))

[2/3 + (-1/2 - sqrt(3)*I/2)*(8/27 + sqrt(237)*I/9)**(1/3) +
13/(9*(-1/2 - sqrt(3)*I/2)*(8/27 + sqrt(237)*I/9)**(1/3)), 2/3 +
13/(9*(-1/2 + sqrt(3)*I/2)*(8/27 + sqrt(237)*I/9)**(1/3)) + (-1/2 +
sqrt(3)*I/2)*(8/27 + sqrt(237)*I/9)**(1/3), 2/3 + 13/(9*(8/27 +
sqrt(237)*I/9)**(1/3)) + (8/27 + sqrt(237)*I/9)**(1/3)]

The values of each are the same:

>>> sorted([w.n(2,chop=True) for w in solve(-x**3+2*x**2+3*x-2)])
[-1.3, 0.53, 2.8]
>>> sorted([w.n(2,chop=True) for w in cutrig(-1,2,3,-2)])
[-1.3, 0.53, 2.8]
smichr
  • 16,948
  • 2
  • 27
  • 34
  • is it possible to use combination of simplify and solve to figure out exactly the real roots of cubic equation? basically the complex part should cancel out itself. – denfromufa Dec 28 '14 at 20:32
  • 1
    See "https://en.wikipedia.org/wiki/Cubic_function": When a cubic equation has three real roots, the formulas expressing these roots in terms of radicals involve complex numbers. It has been proved that when none of the three real roots is rational—the casus irreducibilis— one cannot express the roots in terms of real radicals. Nevertheless, purely real expressions of the solutions may be obtained using hypergeometric functions,[29] or more elementarily in terms of trigonometric functions, specifically in terms of the cosine and arccosine functions. – smichr Jan 06 '15 at 16:27