DoubleOseven DoubleOseven - 3 months ago 7
C++ Question

Newtons method in C++

Hi I have checked numerous other questions but can't seem to figure out why my implementation will not converge. I keep getting the "Error, no convergence" part of my program even when I enter the root.

The function is y = x^2 - 1

Here is the code:

// Newton sqaure root finder function

#include <iostream>
#include <cmath>

int main()
{
using namespace std;

// Enter an initial guess x
cout << "Enter an initial guess: ";
double x;
cin >> x;


// Define & initialize the error, tolerance and iteration variables
double tol = 1e-12;
cout << 1e-12;
double error = tol + 1;
int it = 0;
int max_it = 100;

// Define the x1 variable to hold the latest result (root approximation)
double x1;

// Start while loop with guess x to find the root
while (error > tol && it < max_it)
{
x1 = x + (x*x-1) / (2*x);
error = fabs(x1 - x);
x = x1;
it++;
cout << error << endl;
}

if (error <= tol)
{
cout << "The root is " << x << endl;
}
else
{
cout << "Error, no convergence" << endl;
}

cin.get();
cin.get();

return 0;
}

Answer

You have a typo in the formula

x1 = x + (x*x-1) / (2*x);

it should be

x1 = x - (x*x-1) / (2*x);

You may see it here: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots

Comments