Implement Heron’s Method In the q01 folder, edit the C++ console application to
ID: 3919081 • Letter: I
Question
Implement Heron’s Method
In the q01 folder, edit the C++ console application to calculate and display the square root of a random integer greater than one million, using Heron's Method, to 8 digits of precision to the right of the decimal point.
Specifically you must implement the missing code in the function heron() to return the estimate of the square root of the parameter s.
You may stop iterating when your current x^2 estimate is within 1 x 10 ^ -06 of s
#include "stdafx.h"
using namespace std;
double herons(double s)
{
double x = s / 2;
// TODO: Insert your code here (no greater then e-6
return x;
}
int main()
{
seed_seq seed{ 2016 };
default_random_engine generator{ seed };
uniform_int_distribution<> distribution(1e6, 2e6);
double s = distribution(generator);
cout << fixed << setprecision(0)
<< "The square root of " << s << " is "
<< setprecision(8) << herons(s)
<< endl << endl;
return 0;
}
Explanation / Answer
Please find the modified code below.
CODE
=============
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
double herons(double s)
{
double x = s;
double y = 1;
double e = exp(-6); /* e decides the accuracy level*/
while(x - y > e)
{
x = (x + y)/2;
y = s/x;
}
return x;
}
int main()
{
seed_seq seed{ 2016 };
default_random_engine generator{ seed };
uniform_int_distribution<> distribution(1e6, 2e6);
double s = distribution(generator);
cout << fixed << setprecision(0)
<< "The square root of " << s << " is "
<< setprecision(8) << herons(s)
<< endl << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.