double power(double base, int exponent){
//Just for context, a double is larger than a long long int
//Also method programmed to assume non-decimal, non-negative input for root
double answer = base;
if(exponent == 0){
return 1.0;
}
else if(exponent > 0){
for(int i=1; i<exponent; i++){
answer*=base;
}
return answer;
}
else{//if exponent is negative
for(int i=1; i<exponent*(-1); i++){
answer*=base;
}
return 1/answer;
}
}
double newtonRaphsonRoot(double base, int root){//FOR FIDING ROOTS OF CONSTANT #s
if(base == 1){
return 1.0;
}
//Formula: x1 = x0 - f(x0)/f'(x0)
//--------------------------------
//Also method programmed to assume non-negative integer input for root
double epsilon=0.01;//accuracy
double answer = base;//answer starts off as initial guess and becomes better approximated each iteration
if(base > 1){
answer=base/2;
}
while( answer - ( power(answer,root) - base)/(root*power(answer,root-1) ) > epsilon){
//Formula: x1 = x0 - f(x0)/f'(x0). Continue formula until error is less than epsilon
answer = answer - ( power(answer,root) - base)/(root*power(answer,root-1) );
std::cout<<"Approximation: answer = "<< answer <<"\n";
}
return answer;
}
One problem is that to check for epsilon the code should be
while (fabs(error) > epsilon) {
... improve ...
}
you are instead checking the next approximation against epsilon (also without fabs
).
The other problem is that output stream uses a fixed number of decimals when printing floating point values, if you want to increase that you need to look for std::setprecision
(or just use printf("%.18g\n", x);
that is what I personally prefer to do).