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 /* solve_cubic.c - finds the real roots of x^3 + a x^2 + b x + c = 0 */
24 #include <gsl/gsl_math.h>
25 #include <gsl/gsl_poly.h>
27 #define SWAP(a,b) do { double tmp = b ; b = a ; a = tmp ; } while(0)
30 gsl_poly_solve_cubic (double a, double b, double c,
31 double *x0, double *x1, double *x2)
33 double q = (a * a - 3 * b);
34 double r = (2 * a * a * a - 9 * a * b + 27 * c);
39 double Q3 = Q * Q * Q;
42 double CR2 = 729 * r * r;
43 double CQ3 = 2916 * q * q * q;
54 /* this test is actually R2 == Q3, written in a form suitable
55 for exact computation with integers */
57 /* Due to finite precision some double roots may be missed, and
58 considered to be a pair of complex roots z = x +/- epsilon i
59 close to the real axis. */
61 double sqrtQ = sqrt (Q);
65 *x0 = -2 * sqrtQ - a / 3;
71 *x0 = - sqrtQ - a / 3;
72 *x1 = - sqrtQ - a / 3;
73 *x2 = 2 * sqrtQ - a / 3;
77 else if (CR2 < CQ3) /* equivalent to R2 < Q3 */
79 double sqrtQ = sqrt (Q);
80 double sqrtQ3 = sqrtQ * sqrtQ * sqrtQ;
81 double theta = acos (R / sqrtQ3);
82 double norm = -2 * sqrtQ;
83 *x0 = norm * cos (theta / 3) - a / 3;
84 *x1 = norm * cos ((theta + 2.0 * M_PI) / 3) - a / 3;
85 *x2 = norm * cos ((theta - 2.0 * M_PI) / 3) - a / 3;
87 /* Sort *x0, *x1, *x2 into increasing order */
104 double sgnR = (R >= 0 ? 1 : -1);
105 double A = -sgnR * pow (fabs (R) + sqrt (R2 - Q3), 1.0/3.0);