solve_cubic_equation_real.sf 889 B

12345678910111213141516171819202122232425262728293031
  1. #!/usr/bin/ruby
  2. # Find a real solution to a cubic equation, using reduction to a depressed cubic, followed by the Cardano formula.
  3. # Dividing ax^3 + bx^2 + cx + d = 0 by `a` and substituting `t - b/(3a)` for x we get the equation:
  4. # t^3 + pt + q = 0
  5. # This allows us to use the Cardano formula to solve for `t`, which gives us:
  6. # x = t - b/(3a)
  7. # Example (with x = 79443853):
  8. # 15 x^3 - 22 x^2 + 8 x - 7520940423059310542039581 = 0
  9. # See also:
  10. # https://en.wikipedia.org/wiki/Cubic_function
  11. func solve_cubic_equation (a, b, c, d) {
  12. var p = (3*a*c - b*b)/(3*a*a)
  13. var q = (2*b**3 - 9*a*b*c + 27*a*a*d)/(27 * a**3)
  14. var t = (cbrt(-(q/2) + sqrt((q**2 / 4) + (p**3 / 27))) +
  15. cbrt(-(q/2) - sqrt((q**2 / 4) + (p**3 / 27))))
  16. var x = (t - b/(3*a))
  17. return x
  18. }
  19. say solve_cubic_equation(15, -22, 8, -7520940423059310542039581).round #=> 79443853