Implement a recursive function to compute the cube root of a positive real numbe
ID: 3626662 • Letter: I
Question
Implement a recursive function to compute the cube root of a positive real number greater than or equal to 1 using a bisection (i.e., binary search) approach. You may consider the calculated cube root x accurate enough if x3 is within 0.0001 of the original number (You might find the fabs() function useful for that). The main() function should prompt the user for a real number, call the function to compute the cube root, and display the cube root in an appropriate message.Start with the template program.
What to hand in:
A C++ program named a5q3.cpp containing the C++ program.
Explanation / Answer
#include<iostream>
#include<cmath>
using namespace std;
int a;
inline double f(double x)
{
return (x*x*x-a);
}
double bisect(double a,double b)
{
double c;
c=(a+b)/2.0;
if(fabs(f(c))<0.0001)
return c;
else if(f(a)*f(c)<0.0)
return bisect(a,c);
else
return bisect(c,b);
}
int main()
{
cout << " Enter a Positive Real number :";
cin >> a;
for( int i=1; i<100; i++)
{
if((i*i*i < a ) && (a < (i+1)*(i+1)*(i+1)))
{
cout<<"Root is at : "<<bisect(i,i+1)<<endl;
break;
}
}
return 0;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.