I've been asked to write a rectangle method algorithm to calculate estimated area of function, however, my lecturer sent my code back and asked me to correct it, because ending condition is wrong?
double prostokaty(double( *f)(double))
{
double krok, p, suma = 0;
krok = (c_do - c_od) / lp;
for (p = c_od + krok; p < c_do; p += krok) {
suma += (*f)(p);
}
return suma * krok;
}
I've spent almost two hours, figuring out whats wrong and I failed.
Better to use the middle c_od + krok/2
of the rectangle rather than the right edge c_od + krok
.
double prostokaty(double( *f)(double)) {
double p, suma = 0;
double krok = (c_do - c_od) / lp;
// for (p = c_od + krok; p < c_do; p += krok) {
for (p = c_od + krok/2; p < c_do; p += krok) {
suma += (*f)(p);
}
return suma * krok;
}
If lp
is an integer type, better to avoid accumulated increment errors.
double suma = 0;
double krok = (c_do - c_od) / lp;
for (int i = 0; i < lp; i++) {
double p = c_od + (i + 0.5)*krok;
suma += f(p);
}
return suma * krok;