0

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;
}
1
  • 2
    Because of how floating point numbers work, there is little chance that x ever equals 0. You might want to compare it with an epsilon value instead, eg. fabs(x) < some_epsilon_you_chose. Commented Sep 26, 2013 at 0:10

2 Answers 2

2

In general, testing for equality with floating point arithmetic is a bad idea. I don't know if your math and/or your coding are OK, but I'd guess that the chances are x will never be exactly equal to zero. Consider changing it to something like while (fabs(x) < 1e-10).

Sign up to request clarification or add additional context in comments.

Comments

1

Nickie has a good answer as to what might be your infinite loop problem. I just wanted to add that your use of a while loop is fine in this context because you do not have a clear iteration variable.

Example:

for (int i=0; i < 10; ++i) {
    cout << i << endl;
}

Here it is clear that the variable i represents the iteration because it is the one that is being incremented at the end of each iteration as well as the one being tested as a continuation condition.

In contrast, your loop uses x to test for continuation while it is n that is incremented. This is not a clear cut case for a for loop. A for loop in your case would look like this:

double Newton(double z, int p, double &x, double &n) {
    for (x = (x - ((pow (x, p) - z)/(p * (pow (x, (p - 1)))))); x != 0; n++) {
        x = (x - ((pow (x, p) - z)/(p * (pow (x, (p - 1))))));
    }
    return x;
}

This isn't terrible either but I think the while loop is clearer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.