I have to find the nth root of a number , it is passing some of the test cases but failing for some when x=0.09 and n=3 I am getting ans as 0.09 but expected is 0.448140475. I am not able to figure out why bs is not working Please help!
#include <iostream>
#include <vector>
#include<algorithm>
#include<iomanip>
#include<cmath>
using namespace std;
double solve(double x, int n){
int iter=200;
double low=0;
double high=x;
while(iter--){
double mid = (low+high)/2;
double val = pow(mid,n);
cout<<val<<endl;
if(val<x)low=mid;
else high=mid;
}
return low;
}
int main() {
// int t--;
int t;
cin>>t;
while(t--){
double x;
cin>>x;
int n;
cin>>n;
cout<<fixed<<setprecision(12)<<solve(x,n)<<endl;
}
return 0;
}
Firstly, I suppose that you are trying to utilize the bisection method, not binary search.
Secondly, In mathematical perspective, in order to find the actual root, the initial bisection domain should contain the root from the beginning. However your bisection domain is too small to contain the actual root. (for 0<x<1, the nth root is bigger than the x.)
Lastly, It seems to me that this post has to be moved to the stack exchange which deals the numerical analysis problems. (there is a Computational Science Stack Exchange for that.)