In: Computer Science
In C++
In this assignment, we will implement a square root approximater and then an nth root approximater. Recall that the nth root of x is the number when raised to the power n gives x. We can use the concepts of binary search to approximate the square root of a number, and we can continue this logic to approximate the nth square root. We're going to use the concepts of binary search to try and approximate ending the square root and ending the nth root.
You may not use any library functions for these question, except DecimalFormat.
Commenting your code is a graded requirement. You must detail each operation, loop, conditional statement and function with the desired outputs given input ranges, as well as state its purpose.
#include<bits/stdc++.h>
using namespace std;
void findRoot(double x, double n)
{
// Initialize boundary values
double low, high;
// if x is in between 0 and 1 then
//the function x^n becomes monotonically decreasing
if (x >= 0 and x <= 1)
{
low = x;
high = 1;
}
else
{
low = 1;
high = x;
}
// used for taking approximations of the answer
double epsilon = 0.00000001;
// Performing binary search
double mid = (low + high) / 2;
//loop until the difference becomes less than 0.00000001
while (abs((pow(mid, n)) - x) >= epsilon)
{
// if result is greater make high as the computed result
if (pow(mid, n) > x)
{
high = mid ;
}
// if result is smaller or equal make low as the computed result
else
{
low = mid ;
}
mid = (low + high) / 2;
}
// Printing the result
cout << fixed << setprecision(16) << mid;
}
// Driver code
int main()
{
double x, n;
cout << "Enter the value of n: ";
cin >> n;
cout << "Enter the value of x: ";
cin >> x;
// Function to compute nth root of x
findRoot(x, n) ;
}
OUTPUT: