gsl_poly__solve_quadratic.c 2.0 KB

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