Our instructor wants us to write own sqrt code.
His instructions: Write your own square root function named double my_sqrt_1(double n) using the following pseudocode:
if n < 1 then lower_bound is n, otherwise lower_bound is
1 + (n – 1) / 2 – (n – 1)2 / 8
upper_bound is (n + 1) / 2
repeat 10 times:
midpoint = average of upper_bound and lower_bound
if midpoint2 > n then upper_bound = midpoint
if midpoint2 < n then lower_bound = midpoint
return midpoint
and then write a main which prints n, sqrt(n), and my_sqrt_1(n) for n =
π times 10 to the kth power for k = -100, -10, -1, 0, 1, 10, and 100. Use this C++11 code (which may not work on Visual Studio):
for(auto k : {-100, -10, -1, 0, 1, 10, 100}){
n = M_PI * pow(10.0, k);
//cout goes here
}
So I started it, but it won't run, and I'm not sure why, I am new to c++
but here is what I have so far:
Note that the "std_lib" has the iostream, etc. in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
#include "std_lib_facilities_4.h"
double my_sqrt_1(double n);
{
if (n < 1)
{
lower_bound (n);
}
else
{
lower_bound (1+(n-1)/2-(n-1)*pow(2)/8);
upper_bound ((n+1)/2);
}
double x =1;
for (int i = 0; i < 10; ++i)
{
x = (x+n/x)/2;
return x;
}
}
int main()
{
double n;
for(auto k: {-100, -10, -1, 0, 1, 10, 100})
{
n = M_PI*pow(10.0, k);
cout << n << " ," << sqrt(n) << " ," << my_sqrt_1(n) << '\n';
}
}
|