Question: The code I was provided seems to have a problem. The percentage relative error cannot be negative. The picture below is the result of me

The code I was provided seems to have a problem. The percentage relative error cannot be negative. The picture below is the result of me running the c++ code
I want to be provided with the correct code.
The c++ code I received:
--------------------------------
#include
#include
#include
using namespace std;
// Function to be integrated
double f(double x){
return 1.6* x * x * exp(x);
}
// Simpson's 1/3 rule
double simpsonsRule(double a, double b, int n){
double h =(b - a)/ n;
double sum = f(a)+ f(b);
for (int i =1; i n; i +=2){
sum +=4* f(a + i * h);
}
for (int i =2; i n -1; i +=2){
sum +=2* f(a + i * h);
}
return (h /3)* sum;
}
int main(){
double trueValue =(1.36* exp(1.6))-2;
vector h_values ={0.16,0.08,0.04,0.02,0.01};
vector n_values;
vector errors;
vector relative_errors;
// Calculating n values
for (double h : h_values){
n_values.push_back(static_cast((1-0)/ h));
}
// Calculating integrals and errors
cout "h\tIntegral\tRelative Error (%)
";
for (int n : n_values){
double integral = simpsonsRule(0,1, n);
double error = fabs(integral - trueValue);
double relative_error =(error / fabs(trueValue))*100;
errors.push_back(error);
relative_errors.push_back(relative_error);
cout (1.0/ n)"\t" integral "\t" relative_error "
";
}
// Calculating rate of change of percentage relative error
cout "
Rate of Change of Percentage Relative Error:
";
for (size_t i =1; i relative_errors.size(); ++i){
double rate =(relative_errors[i]- relative_errors[i -1])/(h_values[i]- h_values[i -1]);
cout "From h =" h_values[i -1]" to h =" h_values[i]": " rate "
";
}
return 0;
}
-----------------------------------------
 The code I was provided seems to have a problem. The

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!