Debian Codegraph @

external/gsl/gsl_poly__solve_quadratic.c

raw
1 /* poly/solve_quadratic.c
2 *
3 * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
4 *
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.
9 *
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.
14 *
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.
18 */
19
20 /* solve_quadratic.c - finds the real roots of a x^2 + b x + c = 0 */
21
22 #include "gsl__config.h"
23 #include <math.h>
24
25 #include "gsl_poly.h"
26
27 int
28 gsl_poly_solve_quadratic (double a, double b, double c,
29 double *x0, double *x1)
30 {
31 double disc = b * b - 4 * a * c;
32
33 if (a == 0) /* Handle linear case */
34 {
35 if (b == 0)
36 {
37 return 0;
38 }
39 else
40 {
41 *x0 = -c / b;
42 return 1;
43 };
44 }
45
46 if (disc > 0)
47 {
48 if (b == 0)
49 {
50 double r = fabs (0.5 * sqrt (disc) / a);
51 *x0 = -r;
52 *x1 = r;
53 }
54 else
55 {
56 double sgnb = (b > 0 ? 1 : -1);
57 double temp = -0.5 * (b + sgnb * sqrt (disc));
58 double r1 = temp / a ;
59 double r2 = c / temp ;
60
61 if (r1 < r2)
62 {
63 *x0 = r1 ;
64 *x1 = r2 ;
65 }
66 else
67 {
68 *x0 = r2 ;
69 *x1 = r1 ;
70 }
71 }
72 return 2;
73 }
74 else if (disc == 0)
75 {
76 *x0 = -0.5 * b / a ;
77 *x1 = -0.5 * b / a ;
78 return 2 ;
79 }
80 else
81 {
82 return 0;
83 }
84 }
85