So.Dudes heres the deal.Yesterday a friend of mine wanted me to help him with a function that calculates square root of a positive number using Newton's method.So I came up with this:
Code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
const double tol = 0.000005;
double value;
double old_app, new_app;
cout << "Square root of a number"
<< endl << endl;
cout << "Enter a positive number: ";
cin >> value;
if (value < 0.0)
cout << "Cannot find square root of negative number"
<< endl;
else
if (value == 0.0)
cout << "square root of "
<< value
<< " is 0.00"
<< endl;
else
{
old_app = value;
new_app = (old_app + value/old_app)/2;
while (fabs((new_app-old_app)/new_app) > tol)
{
old_app = new_app;
new_app = (old_app + value/old_app)/2;
}
cout << "square root of "
<< value
<< " is " << new_app
<< endl;
system ("pause");
}
}
But I'm really new in C++ and I'm not sure if this is the right way to represent this algorithm?