fork download
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. int main()
  5. {
  6. double p, q, u, v;
  7. double a = 1.0, b = -6.0, c = 11.0, d = -6.0;
  8.  
  9. p = (3.0 * a * c - b * b) / (3.0 * a * a); // (3ac - b^2) / 3a^2
  10. q = (27.0 * a * a * d + 2.0 * b * b * b - 9.0 * a * b * c) / (27.0 * a * a * a); // (27.0 * a^2 * d + 2 * b^3 -9.0 * a * b * c) / 27a^3
  11.  
  12. std::cout << "p = " << p << ", q = " << q << std::endl;
  13.  
  14. u = std::pow(-q / 2.0 + std::sqrt(std::pow(q / 2.0, 2.0) + std::pow(p / 3.0, 3.0)), 1.0 / 3.0); // (-q/2 + √((q/2)^2 + (p/3)^3))^(1/3)
  15. v = std::pow(-q / 2.0 - std::sqrt(std::pow(q / 2.0, 2.0) + std::pow(p / 3.0, 3.0)), 1.0 / 3.0); // (-q/2 - √((q/2)^2 + (p/3)^3))^(1/3)
  16.  
  17. double x1, x2, x3;
  18.  
  19. x1 = u + v + b / (3.0 * a);
  20.  
  21. std::cout << "x1 = " << x1 << std::endl;
  22. }
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
p = -1, q = 0
x1 = nan