C++ MyProgrammingLab problem Define a recursive function double root( double x,
ID: 3562456 • Letter: C
Question
C++ MyProgrammingLab problem
Define a recursive function
double root(double x, int n, double lower, double upper);
that finds the nth root of x to at least 5 digits of precision.
As a precondition, the parameters lower and upper are such that lower^n <= x and upper^n >=x.
You may want to define a recursive a helper function to compute nth powers.
Hint: try a divide and conquer approach similar to the code for square root.
Use only basic operations +, -, * in your code; no <cmath> or other library functions.
By <cmath>, that means you cannot use built in functions including pow, abs, or other math functions.
Don't write the entire program, just the code for the function.
Explanation / Answer
double root(double x, int n, double lower, double higher)
{
double sum;
double limit=0.00001;
double low=npower(lower, n);
double high=npower(higher, n);
if(low <=x || high >=x)
{
sum=nroot(x,n);
}
return sum;
}
double nroot(double x, int n)
{
double result = 1;
double result_n;
boolean accurate = false;
while (!accurate)
{
result_n = (1 / (double)n) * ((n - 1) * result+ x /npow(result, n - 1));
accurate = accurate(result, result_n);
result = result_n;
}
return result;
}
}
double npower(double x, int n)
{
if(n!=0)
x=x*(n-1);
return x;
}
private static boolean accurate(double result , double result_n)
{
return (result_n-result) < 0.00001;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.