3 * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or (at
8 * your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 /* zsolve_cubic.c - finds the complex roots of x^3 + a x^2 + b x + c = 0 */
24 #include <gsl/gsl_math.h>
25 #include <gsl/gsl_complex.h>
26 #include <gsl/gsl_poly.h>
28 #define SWAP(a,b) do { double tmp = b ; b = a ; a = tmp ; } while(0)
31 gsl_poly_complex_solve_cubic (double a, double b, double c,
32 gsl_complex *z0, gsl_complex *z1,
35 double q = (a * a - 3 * b);
36 double r = (2 * a * a * a - 9 * a * b + 27 * c);
41 double Q3 = Q * Q * Q;
44 double CR2 = 729 * r * r;
45 double CQ3 = 2916 * q * q * q;
49 GSL_REAL (*z0) = -a / 3;
51 GSL_REAL (*z1) = -a / 3;
53 GSL_REAL (*z2) = -a / 3;
59 /* this test is actually R2 == Q3, written in a form suitable
60 for exact computation with integers */
62 /* Due to finite precision some double roots may be missed, and
63 will be considered to be a pair of complex roots z = x +/-
64 epsilon i close to the real axis. */
66 double sqrtQ = sqrt (Q);
70 GSL_REAL (*z0) = -2 * sqrtQ - a / 3;
72 GSL_REAL (*z1) = sqrtQ - a / 3;
74 GSL_REAL (*z2) = sqrtQ - a / 3;
79 GSL_REAL (*z0) = -sqrtQ - a / 3;
81 GSL_REAL (*z1) = -sqrtQ - a / 3;
83 GSL_REAL (*z2) = 2 * sqrtQ - a / 3;
88 else if (CR2 < CQ3) /* equivalent to R2 < Q3 */
90 double sqrtQ = sqrt (Q);
91 double sqrtQ3 = sqrtQ * sqrtQ * sqrtQ;
92 double theta = acos (R / sqrtQ3);
93 double norm = -2 * sqrtQ;
94 double r0 = norm * cos (theta / 3) - a / 3;
95 double r1 = norm * cos ((theta + 2.0 * M_PI) / 3) - a / 3;
96 double r2 = norm * cos ((theta - 2.0 * M_PI) / 3) - a / 3;
98 /* Sort r0, r1, r2 into increasing order */
124 double sgnR = (R >= 0 ? 1 : -1);
125 double A = -sgnR * pow (fabs (R) + sqrt (R2 - Q3), 1.0 / 3.0);
130 GSL_REAL (*z0) = A + B - a / 3;
133 GSL_REAL (*z1) = -0.5 * (A + B) - a / 3;
134 GSL_IMAG (*z1) = -(sqrt (3.0) / 2.0) * fabs(A - B);
136 GSL_REAL (*z2) = -0.5 * (A + B) - a / 3;
137 GSL_IMAG (*z2) = (sqrt (3.0) / 2.0) * fabs(A - B);
141 GSL_REAL (*z0) = -0.5 * (A + B) - a / 3;
142 GSL_IMAG (*z0) = -(sqrt (3.0) / 2.0) * fabs(A - B);
144 GSL_REAL (*z1) = -0.5 * (A + B) - a / 3;
145 GSL_IMAG (*z1) = (sqrt (3.0) / 2.0) * fabs(A - B);
147 GSL_REAL (*z2) = A + B - a / 3;