Do/while trouble with Newton's Method

I am new to C++. I need to create a program that checks how effective Newton's method is for finding the root of a polynomial. I came up with some basic code to do so. However, it seems my do/while loop terminates too early. I am unsure as to why.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <math.h>

int main(int argc, const char * argv[])
{
    // Equation being used for Newton's method is f(x)= x*x-4
    // f'(x) = 2*x
    
    const double epsilon = .00001;
    // Declares the how close the approximation should be
    double x0;
    double x1;
    double rt = 2;

    
    // Input the initial condition
    std::cout << "What is the initial value of x?";
    std::cin >> x0;                                
    
   do {
       //Run the Newton method formula
        x1 = x0 - ( (x0 * x0 - 4)/ (x0 * 2));
        //Set the new value of x0
        x0 = x1;
        //output the approximation
        std::cout << "x1 = " << std::fixed << x1 << "." << std::endl;
   }while (abs(abs(x1)- rt) >= epsilon);
    //Keep looping while the absolute difference between the rt 
    //and the absolute approximation is greater than or equal to epsilon
    
    return 0;
}
Can you give an exmple of your outputs?
If I input 4 it outputs x1 = 2.500000. Or if I input a larger number such as 50 it outputs x1 = 25.040000. x1 = 12.599872. x1 = 6.458668. x1 = 3.538995. and x1 = 2.334630. These outputs are following the Newton's method formula. However, the loop keeps stopping before I want it to. I don't understand why. For example, with x0=4 the output is 2.5. 2.5 - 2 is greater than epsilon. Therefore the loop should continue, no?
I think I know why. From this reference:
http://cplusplus.com/reference/cstdlib/abs/?kw=abs

Abs() returns an int, essentially rounding your number. Therefore, if you enter 1 or 4, the resultant condition becomes: abs(2 - 2) >= 0.00001

Edit:
To get the absolute value of a decimal, you need fabs(). See reference below.
http://cplusplus.com/reference/cmath/fabs/
Last edited on
Thanks!! That was exactly the issue. I switched out abs with fabs and it works fine.
Thanks!! That was exactly the issue. I switched out abs with fabs and it works fine.


If you'd used the C++ header cmath rather than the C header math.h you wouldn't have run into that issue.

http://www.cplusplus.com/reference/cmath/abs/
Topic archived. No new replies allowed.