Programming language is C++. The code for problem 2 is posted below. Show finish
ID: 3788315 • Letter: P
Question
Programming language is C++. The code for problem 2 is posted below. Show finished code and an example of the output on PuTTY when done. Use g++ -std=c++17 -Wall -Wextra -pedantic -fsanitize=address,undefined to compile the code on PuTTY.
#include<iostream>
#include<cmath>
#include <stdlib.h>
using namespace std;
/*
Calculate cube root using Pade approximation
*/
double my_cbrt_l(double n)
{
double numerator = (101.639 * n * n) + (207.953*n) + 29.7541;
double denominator = (-1 * n * n *n) + (42.945* n *n) + (215.165* n) + 92.1357;
double result = numerator / denominator;
return result;
}
int main(void)
{
double n;
cout << "Pi value in my system:" << M_PI << endl;
for (auto k : { -100,-10,-1,0,1,10,100 }) {
n = M_PI * pow(10.0, k);
cout << "By library function cube root of " << n << " is:" << cbrt(n) << endl;
cout << "By Pade approximant cube root of " << n << " is:" << my_cbrt_l(n) << endl;
cout << "====================================================" << endl;
}
return 0;
try {
return 0;
}
catch (exception&e) {
cerr << "error:" << e.what() << ' ';
keep_window_open();
return 1;
}
catch (...) {
cerr << "Oops:unknown exception! ";
keep_window_open();
return 2;
}
}
Explanation / Answer
#include "std_lib_facilities_4.h"
//A function which reads in a double and outputs a square root 10 times
double my_cbrt_1(double n)
{
//Initializing variables in the scope of the function
double x = 1;
//Repeat
//Uses a counter to repeat the function 10 times
for (int count = 1 ; count == 10 ; count++)
{
//Square root function
//Computes square root
x = (x + n/x)/2;
}
//Returns the value computed above
return x;
}
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_cbrt_1(n) - cbrt(n)) / cbrt(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 " << cbrt(n) << endl
<< "The value of my square root is " << my_cbrt_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;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.