gsl_poly__zsolve_quadratic.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /* poly/zsolve_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. /* complex_solve_quadratic.c - finds complex roots of a x^2 + b x + c = 0 */
  20. #include "gsl__config.h"
  21. #include <math.h>
  22. #include "gsl_complex.h"
  23. #include "gsl_poly.h"
  24. int
  25. gsl_poly_complex_solve_quadratic (double a, double b, double c,
  26. gsl_complex *z0, gsl_complex *z1)
  27. {
  28. double disc = b * b - 4 * a * c;
  29. if (a == 0) /* Handle linear case */
  30. {
  31. if (b == 0)
  32. {
  33. return 0;
  34. }
  35. else
  36. {
  37. GSL_REAL(*z0) = -c / b;
  38. GSL_IMAG(*z0) = 0;
  39. return 1;
  40. };
  41. }
  42. if (disc > 0)
  43. {
  44. if (b == 0)
  45. {
  46. double s = fabs (0.5 * sqrt (disc) / a);
  47. GSL_REAL (*z0) = -s;
  48. GSL_IMAG (*z0) = 0;
  49. GSL_REAL (*z1) = s;
  50. GSL_IMAG (*z1) = 0;
  51. }
  52. else
  53. {
  54. double sgnb = (b > 0 ? 1 : -1);
  55. double temp = -0.5 * (b + sgnb * sqrt (disc));
  56. double r1 = temp / a;
  57. double r2 = c / temp;
  58. if (r1 < r2)
  59. {
  60. GSL_REAL (*z0) = r1;
  61. GSL_IMAG (*z0) = 0;
  62. GSL_REAL (*z1) = r2;
  63. GSL_IMAG (*z1) = 0;
  64. }
  65. else
  66. {
  67. GSL_REAL (*z0) = r2;
  68. GSL_IMAG (*z0) = 0;
  69. GSL_REAL (*z1) = r1;
  70. GSL_IMAG (*z1) = 0;
  71. }
  72. }
  73. return 2;
  74. }
  75. else if (disc == 0)
  76. {
  77. GSL_REAL (*z0) = -0.5 * b / a;
  78. GSL_IMAG (*z0) = 0;
  79. GSL_REAL (*z1) = -0.5 * b / a;
  80. GSL_IMAG (*z1) = 0;
  81. return 2;
  82. }
  83. else
  84. {
  85. double s = fabs (0.5 * sqrt (-disc) / a);
  86. GSL_REAL (*z0) = -0.5 * b / a;
  87. GSL_IMAG (*z0) = -s;
  88. GSL_REAL (*z1) = -0.5 * b / a;
  89. GSL_IMAG (*z1) = s;
  90. return 2;
  91. }
  92. }