So i need help doing this project and heres what i have to do for the program i left some comments on what my code does etc, please help.
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.
#include <iostream>
using namespace std;
double square_root(double x, double initial_guess, double error);
double absolute(double difference);
double x, initial_guess, error;
double next_guess;
double difference;
int count = 0;
int main()
{
cout << "Enter a number to square root: ";
cin >> x;
cout << "Enter a number for intitial_guess: ";
cin >> initial_guess;
cout << "Enter a number for error: ";
cin >> error;
square_root(x, initial_guess, error);
cout << "The square root of " << x << " is " << next_guess << " after " << count << " try" << endl;
return 0;
}
double square_root(double x, double initial_guess, double error)
{
do
{
next_guess = (initial_guess + x / initial_guess) / 2;
count++; // this is the keep track of how many times i did the calculation until i get the closest sqrt value for x
if(absolute(next_guess - initial_guess) < error)
{
break;
}
}
while (difference > error);
return 0;
}
double absolute(double difference)
{
if(difference < error)
{
return next_guess; // if its true it returns the sqrt value of the number the user entered for x
}
else
{
// if false it should continue to with the repetition but i don't know how to do that
// i need some help
}
}