Advertisement
LEGEND2004

The root of a cubic equation

Feb 26th, 2023
689
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define int long long
  5. #define double long double
  6.  
  7. int a , b , c , d;
  8.  
  9. double f(double x , int a , int b , int c , int d){
  10.     double s = a * x * x * x + b * x * x + c * x + d;
  11.     return s;
  12. }
  13.  
  14. signed main()
  15. {
  16.     cout.precision(6);
  17.     cin >> a >> b >> c >> d;
  18.     double r = 1.0;
  19.     while(true){
  20.         if((f(r , a , b , c , d) * f(-r , a , b , c , d)) < 0){
  21.             break;
  22.         }else{
  23.             r *= 2;
  24.         }
  25.     }
  26.     double l = -r;
  27.     while((l + 1e-6) <= r){
  28.         double m = (l + r) * 1.0 / 2;
  29.         if((f(m , a , b , c , d) * f(-m , a , b , c , d)) < 0){
  30.             r = m;
  31.         }else{
  32.             l = m;
  33.         }
  34.     }
  35.     double x = abs(f(l , a , b , c , d)) , y = abs(f(-l , a , b , c , d));
  36.     if(x > y)
  37.         l = -l;
  38.     cout << fixed << l << endl;
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement