aurimas13 wrote: |
---|
I understand your given example - it's easy. It should go like this:
1 2 3 4 5 6 7 8 9 10 11 12
|
double simpson2(double start, double end, int steps)
{
double sum = 0.0;
double h = (start - end) / steps;
double h2 = h / 2;
for (int i = 0; i < n; i++)
{
double left = a + i * h;
sum += function(left) + 4 * function(left + h2) + function(left + h);
}
return h / 6 * sum;
}
|
|
Close. However, I requested:
I wrote: |
---|
// compute and return the integral of function fk_2 |
Your code has no
fk_2
anywhere, and then there is a mystery
a
too.
A tricky part about coding is that details are important.
Lets fix those:
1 2 3 4 5 6 7 8 9 10 11 12
|
double simpson2(double start, double end, int steps)
{
double sum = 0.0;
double h = (start - end) / steps;
double h2 = h / 2;
for (int i = 0; i < n; i++)
{
double left = start + i * h;
sum += fk_2(left) + 4 * fk_2(left + h2) + fk_2(left + h);
}
return h / 6 * sum;
}
|
That settled, add the function pointer back to the list of arguments and replace every occurrence of
fk_2
with the name of the pointer:
1 2 3 4 5 6 7 8 9 10 11 12
|
double simpson(double start, double end, int steps, Func fun)
{
double sum = 0.0;
double h = (start - end) / steps;
double h2 = h / 2;
for (int i = 0; i < n; i++)
{
double left = start + i * h;
sum += fun(left) + 4 * fun(left + h2) + fun(left + h);
}
return h / 6 * sum;
}
|
Would that that do what was requested?
Now it would be good, if you would re-read the
http://www.cplusplus.com/articles/Gw6AC542/
Your current homework might not request it, but you could practice this:
Create three files:
simpson.h declare the function simpson here. If you do use the alias Func, put it here too.
simpson.cpp implementation of function simpson.
pratimas_13.cpp the rest: main(), fk_1(), fk_2(), text(), etc
You have to compile the simpson.cpp and the pratimas_13.cpp separately and then link the object files together.