I had a quick question about a seemingly infinite input loop in my program. I's sure it is taking place in the while loop, and am wondering if it is because my math or my coding. While loops are still new to me, so any help or explanation would be nice would be nice! This program is the start of a program using Newton's method to find the pth root of z, the residual,and improvement between loops. Also, I was wondering if a for loop might be better for my purposes. Here it is so far:
#include <iostream>
#include <cmath>
using namespace std;
double Newton(double z, int p, double &x, double &n);
int main(){
double z, x, n, residual, bai, bri;
int p;
x = 1;
n = 1;
cin >> z >> p;
double roots = Newton(z, p, x, n);
cout.precision (5);
cout << "Input: z = " << z << ", p = " << p << endl << "Root = " << x << endl;
}
double Newton(double z, int p, double &x, double &n){
x = (x - ((pow (x, p) - z)/(p * (pow (x, (p - 1))))));
while (x != 0){
x = (x - ((pow (x, p) - z)/(p * (pow (x, (p - 1))))));
n++;
}
return x;
}
xever equals0. You might want to compare it with an epsilon value instead, eg.fabs(x) < some_epsilon_you_chose.