This is a C++ Code on how compute for the area under the curve using integral calculus and trapezoid method. Question 1.
Posted: Sun Jul 03, 2022 9:59 am
This is a C++ Code on how compute for the area under the curveusing integral calculus and trapezoid method.
Question
1. What are your takeaways about this code?
2. explain different codes that have been used in thisprogram.
3. and How a Linked listing stores and display the area of eachtrapezoid
CODE:
#include<iostream>
#include<iomanip>
using namespace std;
float f(float x){
return x + (3 * x * x);
}
float F(float x){
return (x * x / 2) + (x * x * x);
}
int main(){
float a , b;
int n;
cout << "Enter value of a: " ;
cin >> a;
cout << "Enter value of b: ";
cin >> b;
cout << "Specify the number of trapezoids: ";
cin >> n;
cout << endl;
float integral = F(b) - F(a);
float h = (float)((b - a) / n);
float *trapz = new float[n];
float sum_trapz = 0;
int i = 0;
while(a <= b){
float ai = a;
float bi = a + h;
trapz = ((f(ai) + f(bi)) / 2) * (h);
sum_trapz += trapz;
cout << "Trapezoid area " << i + 1 << " = "<< fixed << setprecision(4)
<< trapz << " units squared." << endl;
i++;
a = bi;
}
cout << "\n\nArea using trapezoid method = " <<sum_trapz << " units Squared" << endl;
cout << "The area using integral calculus = " <<integral << " units squared" << endl;
float rel_err = ((integral - sum_trapz) / integral) * 100;
cout << "Percenr error = " << rel_err << "%"<< endl;
cout << "Press any key to continue ...";
char ch;
cin >> ch;
return 0;
}
Question
1. What are your takeaways about this code?
2. explain different codes that have been used in thisprogram.
3. and How a Linked listing stores and display the area of eachtrapezoid
CODE:
#include<iostream>
#include<iomanip>
using namespace std;
float f(float x){
return x + (3 * x * x);
}
float F(float x){
return (x * x / 2) + (x * x * x);
}
int main(){
float a , b;
int n;
cout << "Enter value of a: " ;
cin >> a;
cout << "Enter value of b: ";
cin >> b;
cout << "Specify the number of trapezoids: ";
cin >> n;
cout << endl;
float integral = F(b) - F(a);
float h = (float)((b - a) / n);
float *trapz = new float[n];
float sum_trapz = 0;
int i = 0;
while(a <= b){
float ai = a;
float bi = a + h;
trapz = ((f(ai) + f(bi)) / 2) * (h);
sum_trapz += trapz;
cout << "Trapezoid area " << i + 1 << " = "<< fixed << setprecision(4)
<< trapz << " units squared." << endl;
i++;
a = bi;
}
cout << "\n\nArea using trapezoid method = " <<sum_trapz << " units Squared" << endl;
cout << "The area using integral calculus = " <<integral << " units squared" << endl;
float rel_err = ((integral - sum_trapz) / integral) * 100;
cout << "Percenr error = " << rel_err << "%"<< endl;
cout << "Press any key to continue ...";
char ch;
cin >> ch;
return 0;
}