equation-solver.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include "equation-solver.h"
  2. #define _USE_MATH_DEFINES
  3. #include <cmath>
  4. #ifndef MSDFGEN_CUBE_ROOT
  5. #define MSDFGEN_CUBE_ROOT(x) pow((x), 1/3.)
  6. #endif
  7. namespace msdfgen {
  8. int solveQuadratic(double x[2], double a, double b, double c) {
  9. // a == 0 -> linear equation
  10. if (a == 0 || fabs(b) > 1e12*fabs(a)) {
  11. // a == 0, b == 0 -> no solution
  12. if (b == 0) {
  13. if (c == 0)
  14. return -1; // 0 == 0
  15. return 0;
  16. }
  17. x[0] = -c/b;
  18. return 1;
  19. }
  20. double dscr = b*b-4*a*c;
  21. if (dscr > 0) {
  22. dscr = sqrt(dscr);
  23. x[0] = (-b+dscr)/(2*a);
  24. x[1] = (-b-dscr)/(2*a);
  25. return 2;
  26. } else if (dscr == 0) {
  27. x[0] = -b/(2*a);
  28. return 1;
  29. } else
  30. return 0;
  31. }
  32. static int solveCubicNormed(double x[3], double a, double b, double c) {
  33. double a2 = a*a;
  34. double q = 1/9.*(a2-3*b);
  35. double r = 1/54.*(a*(2*a2-9*b)+27*c);
  36. double r2 = r*r;
  37. double q3 = q*q*q;
  38. a *= 1/3.;
  39. if (r2 < q3) {
  40. double t = r/sqrt(q3);
  41. if (t < -1) t = -1;
  42. if (t > 1) t = 1;
  43. t = acos(t);
  44. q = -2*sqrt(q);
  45. x[0] = q*cos(1/3.*t)-a;
  46. x[1] = q*cos(1/3.*(t+2*M_PI))-a;
  47. x[2] = q*cos(1/3.*(t-2*M_PI))-a;
  48. return 3;
  49. } else {
  50. double u = (r < 0 ? 1 : -1)*MSDFGEN_CUBE_ROOT(fabs(r)+sqrt(r2-q3));
  51. double v = u == 0 ? 0 : q/u;
  52. x[0] = (u+v)-a;
  53. if (u == v || fabs(u-v) < 1e-12*fabs(u+v)) {
  54. x[1] = -.5*(u+v)-a;
  55. return 2;
  56. }
  57. return 1;
  58. }
  59. }
  60. int solveCubic(double x[3], double a, double b, double c, double d) {
  61. if (a != 0) {
  62. double bn = b/a;
  63. if (fabs(bn) < 1e6) // Above this ratio, the numerical error gets larger than if we treated a as zero
  64. return solveCubicNormed(x, bn, c/a, d/a);
  65. }
  66. return solveQuadratic(x, b, c, d);
  67. }
  68. }