Write a program to compute the square root of a number. DO NOT USE any math libraries in this program. You will be using the Babylonian method (a.k.a. Heron’s method) to approximate the square root. More information is available on wikipedia:
http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
To calculate the square root of x, the Babylonian method requires three inputs: x, an initial guess for the square root, and the error (tolerance). It uses a repetitive calculation to get closer and closer to the actual value of the square root:
nextGuess = (lastGuess + x / lastGuess) / 2
After each repetition, the method checks if the absolute value of the difference between nextGuess and lastGuess is less than the error. If so, it stops and returns the value of nextGuess as the square root. If the difference between nextGuess and lastGuess is larger than the error, it repeats the calculation.
Your program needs three functions: main, square root, and absolute value. The main function should get all three inputs from the user(x, initial guess, and error), run the square root function, and output the approximate value of the square root. In addition, the square root function should keep track of how many repetitions are used to calculate the square root value, which should be printed out along with the square root value in the main function. As you can not use any math libraries, you will also need to write your own absolute value function. Only the main function should interact with the user (getting inputs and displaying results). The square root and absolute value functions should not contain any cin or cout statements.
This is what I have so far and kinda stuck on what to do next
I think I did the absolute function part wrong (PLEASE TAKE A LOOK AT IT)
Please help me
#include <iostream>
using namespace std;
void square_root(double x, double initial_guess, double error, double& next_guess);
double absolute(double x, double initial_guess, double error, double next_guess);
double x, initial_guess, error;
double next_guess;
int main()
{
cout << "Enter a number to square root: ";
cin >> x;
cout << "Enter a number for guess: ";
cin >> initial_guess;
cout << "Enter a number for error: ";
cin >> error;
square_root(x, initial_guess, error, next_guess);
absolute(x, initial_guess, error, next_guess);
cout << "Square Root of " << x << " is " << next_guess << endl;
return 0;
}
void square_root(double x, double initial_guess, double error, double& next_guess)
{
next_guess = (initial_guess + x / initial_guess) / 2;
}
double absolute(double x, double initial_guess, double error, double next_guess)
{
next_guess = next_guess - initial_guess;
if (next_guess > error)
{
square_root(x, initial_guess, error, next_guess);
}
if (next_guess < 0)
{
next_guess = next_guess * -1;
square_root(x, initial_guess, error, next_guess);
}
else
{
}
return next_guess;
}