Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Programming language is C++. Show finished code and an example of the output on

ID: 3796327 • Letter: P

Question

Programming language is C++. Show finished code and an example of the output on PuTTY when done. Use g++ -std=c++17 to compile the code on PuTTY.

Write a program named hw3pr4.cpp to determine the smallest number k such that looping k times is just as accurate as looping 10 times. Hint: For k 1 to 10 find the maximum absolute relative error for n from 1.05 to 1.55 in steps of 1/1024 se those 10 numbers to determine the smallest number k such that looping k times is just as accurate as looping 10 times. Name your program hw3pr4.cpp.

Explanation / Answer

main.cpp


#include "std_lib_facilities_4.h"

double my_cbrt_1 (double n ){
  
   double ans;
   ans=1.03455*n+0.377113-0.411665*n*n;
   return ans;
  
}
double my_cbrt_2(double n){
   int result=1;
if (n>1){
   while(n>1){
       result*=2;
       n/=8;      
}
  
}
if (n<(1/8)){
   while (n<(1/8)){
       result/=2;
       n*=8;
   }    
}
   return result*my_cbrt_1(n);
}
  
  
      
  

void bullshit(string s){
   throw runtime_error(s);
  
}
double my_cbrt_3(double n){
   if (n==0){ return 0;}
   if (n<0) {return -my_cbrt_3(-n) ;}
  
       double x;
       x= my_cbrt_2(n);
       for (int i=0; i<10; ++i){
           x=((2.0/3)*x)+(n/(3.0*x*x));
       }
           return x;
}
  
  

int main()
try {
  
double relative_error=0.5; //
double rel_num;//relative error obtained from each iteration of inner loop for n
vector<double>max_num; // list of maximum relative error for each k
double y=100.0;
int index;
double x;
  
  
  
   for (int k=1; k<11; ++k){
       for (int j=1;j<=k; j++){
    for (double n=1.0/8.0; n<=1.0; n+=1.0/1024){
               x= my_cbrt_2(n);
               x=((2/3)*x)+(n/(3*x*x));
           rel_num=abs((x-cbrt(n))/cbrt(n));
                 
              
               if (rel_num > relative_error && rel_num <= abs(my_cbrt_3(n))){
                   relative_error=rel_num;
               }
   }
       }
          
               cout<<"relative error is "<<relative_error<<endl;
  
       max_num.push_back(relative_error);     
   }
  
   for (int i=0; i<10; ++i){
       if(max_num[i]< y){
           y=max_num[i];
index=i+1;          
       }
   }
  
  
   cout<<"The smallest K is "<<index<<", which has the maximum absolute value of "<<y<<endl;
  
   }


catch (runtime_error&e){
   cerr<<"runtime error: "<<e.what()<<endl;
   keep_window_open();
   return 1;
  
}
catch(...){
   cerr<<"Unknown exception! "<<endl;
   keep_window_open();
   return 2;
  
}

=================================================================