Answer the question
In order to leave comments, you need to log in
Is the code for the trapezoid method written correctly in C++?
h = (b - a) / n;
for (int i = 1; i <= (n - 1); i++)
S += f(a + h*i);
integ = h * ((f(a) + f(b)) / 2 + S);
Answer the question
In order to leave comments, you need to log in
At least describe what f() means for you. And so some kind of stub of code, which still needs to be thought out on its own.
An example from the cyberforum.
#include <cmath>
#include <cstdio>
#include <cstdlib>
typedef double(*function)(double);
double integral(function f, double a, double b, unsigned step_count) {
double sum = .0, step;
size_t i;
if (0 == step_count) return sum;
step = (b - a) / (1.0 * step_count);
for ( i = 1 ; i < step_count ; ++i ) {
sum += f (a + i * step);
}
sum += (f(a) + f(b)) / 2;
sum *= step;
return sum;
}
double f (double x) {
return 2 * x;
}
int main() {
printf ("\\int_0^10(x) = %f\n", integral(f, 0, 10, 15));
}
Answering the question: Yes, this piece of code is correct .
Recommendations for the future:
1) When asking a question, it is advisable to write in a little more detail.
2) To check the code, you can make a formula that it implements and compare with the theoretical one.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question