1. Let the number be a (you are given that a 0 2·Let zo = 1. d Cunpate saccesiwe
ID: 3911005 • Letter: 1
Question
1. Let the number be a (you are given that a 0 2·Let zo = 1. d Cunpate saccesiwet 01 T- 4. The iteration clearly goes on forever, so we set a tolerance to stop the iteration 5. Stop the iteration whe ri-1l s 104, 6. Return the value of r, as the approximation to the square root a Write a function to implement the Babylonian algorithm to calculate the square root of a positive nmber double sqrt Babylonian (double a); The function return value is the approximation r, to the square root of a Print the values of the iterates r, inside your function, starting with ro Submit your function code as your answer.Explanation / Answer
Find the required program in C++:
//===========================================================
#include <iostream>
#include <math.h> // Required to calculate absolute value of double type variables
using namespace std;
double sqrt_Babylonian(double a)
{
double x_prev,x_current;
int i=0;
x_prev=1; // x0 = 1
while(1)
{
std::cout << "Value of x("<<i<<") is: "<< x_prev << std::endl;
x_current = (0.5)*(x_prev + (a/x_prev)); // Iterative approximation
if(fabs(x_prev-x_current)<=0.0001) // Tolerance check
{
break;
}
x_prev=x_current;
i=i+1;
}
return(x_current);
}
int main() {
double a;
std::cout << "Please enter the value of 'a': " << std::endl;
std::cin >> a;
std::cout << "The approximate value of a^(1/2) as returned by function is:"<<sqrt_Babylonian(a) << std::endl;
return 0;
}
//==========================================================
Sample output for a=2;
Please enter the value of 'a': 2
Value of x(0) is: 1
Value of x(1) is: 1.5
Value of x(2) is: 1.41667
Value of x(3) is: 1.41422
The approximate value of a^(1/2) as returned by function is:1.41421
Hope this helps! **************** Please thumbs up! ****************
In case of further clarification, please comment!
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.