int main(){ for (auto k : { -100, -10, -1, 0, 1, 10, 100 }){ double n = MPI * pow(10.0, k); std::cout << n << "\n" << sqrt(n) << "\n" << my_sqrt_1(n) << "\n"; } return 0; }
int main() { //Error Check //Runs program until it's finished or error is found //Goes through catch to find source of error //If error is found tells user of error before quitting try { //Initializing variables double n = 0; double relative_error_per_cent = 0; //Repeat //For a list of values, the function is computed for(auto k : {-100, -10, -1, 0, 1, 10, 100}) { //Computes function for finding n = M_PI * pow(10.0, k); relative_error_per_cent = 100 * ( (my_sqrt_1(n) - sqrt(n)) / sqrt(n) ); //Outputs //Prints values of n, square root of n and the function square root of n cout << "The value of n is " << n << endl << "The value of the square root n is " << sqrt(n) << endl << "The value of my square root is " << my_sqrt_1(n); cout << setw(40) << "The relative error is " << relative_error_per_cent << endl; } } catch (exception& e) { cerr << "error: " << e.what() << endl; return 1; } catch(...) { cerr << "Oops: unknown exception!" << endl; return 2; } return 0; }
double my_sqrt_2( double n ) // To calculate square root of n by the given formula { double result = 1.00; while( n > 8/5 ) { result *= 2 ; n = n / 4 ; } while( n < 2/5 ) { result /= 2; n = n * 4; } return result * my_sqrt_1( n ); //calls the function my_sqrt_1(n) which returns a value, which is multiplied with the result and returned where the function is called }