C++ MyProgrammingLab problem Define a recursive function double root( double x,
ID: 3562584 • 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 and abs.
Do not write the entire program.
Here is my solution for this problem:
double power(double x, int n)
{
if(n < 0)
{
return 1.0 / power(x,-n);
}
if(n == 0)
{
return 1.0;
}
return x * power(x,n-1);
}
double root(double x, int n, double lower, double upper)
{
const double epsilon = 0.00001;
double low = power(lower,n);
double high = power(upper,n);
double total = low+high;
double average = (total)/2;
double temp = power(average,n);
if(x-temp > epsilon && x-temp < epsilon)
{
if(temp > x)
{
high = average;
return root(x,n,low,high);
}
else
{
low = average;
return root(x,n,low,high);
}
}
else
{
return x;
}
return average;
}
MyProgrammingLab is not accepting this solution. Can someone please post the correct answer to this problem?
Explanation / Answer
#include #include using namespace std; //Define function f(x) double f(double x, double a, double b) { return sin((a*x)/(1+x*x))*atan(b*x)+atan(x); } int main() { //Input a,b parameters constants, lower and upper approximation points as well as a precision value N double a, b, N, lowerB, upperB; cout a; cout b; cout N; cout lowerB >> upperB; double RootFinderSMNew(double f, double a, double b, double lowerB, double upperB, int N); { double f_left=f(lowerB, a, b),now=lowerB+N,f_right=f(now, a, b); while(f_left*f_right>0 && nowRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.