Okay I think I have everything done, but how do you set a tolerance? Like I have to set a tolerance of 10^-6 (6 decimal places). Would it be like:
Code:
#define TOLERANCE 10^-6
? That's what I tried but I couldn't get it to work. I'll post the code I have now...
Code:
#include<iostream>
#include<cmath>
void getInitGuess(double&);
double f(double, int, int);
double fPrime(double, int, int);
void findRoots(double&, int, int);
using namespace std;
int main(){
double root, guess;
int c, n;
cout << "Enter the number to find the nth root of: ";
cin >> c;
cout << "Enter n (the degree of the root): ";
cin >> n;
findRoots(guess, n, c);
root = guess;
cout << "The " << n << " root of " << c << " is: " << root << endl;
return 0;
}
void getInitGuess(double& guess){
cout << "Enter your initial guess: ";
cin >> guess;
}
double f(double x, int n, int c){
double fx;
fx = pow(x, n) - c;
return fx;
}
double fPrime(double x, int n, int c){
double fp;
fp = n * pow(x, (n-1));
return fp;
}
void findRoots(double& x, int n, int c){
double TOLERANCE = .000001; //Here is where I defined tolerance, but is this right?
x = 0;
for(int i=0; i < TOLERANCE; i++){
x -= (f(x, n, c) / fPrime(x, n, c));
if(abs(x) <= TOLERANCE)
break;
}
}
When I run it as it is, this happens:
-------
Enter the number to find the nth root of: 2
Enter n (the degree of the root): 2
The 2 root of 2 is 1.#INF
The answer is the same for 3rd root of 7 and 3rd root of -1
What is #INF? How could I fix this? I think this is all I'm lacking now.