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.
#include <iostream>
#include <math.h>
int main(int argc, constchar * argv[])
{
// Equation being used for Newton's method is f(x)= x*x-4
// f'(x) = 2*x
constdouble 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;
}
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?