equation-solver.cpp 1.8 KB

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