How to write a feature for calculating a specific integral by Simpson?

## Answer 1, Authority 100%

There is a known Formula To calculate the value of the integral at some `interface [ A, B] `

. Your task is to split the original segment `[a, b] `

on a certain amount of the links `[a_n, b_n `

] and on each of them to count the value of the integral using the Simpson formula. Next, you must fold all the values.

Depending on the selected partition, the accuracy of the final response will vary. Here, by the way, there is a more interesting task of *about the choice of the necessary segments to maximize accuracy when minimizing the number of calculations, *which, however, requires some knowledge of numerical methods and theory for working with errors.

*Your function in the C++ may look something like this: *

```
typedef float float_t;
TypeDef ... Function_T;
float_t partintegraatewithsimpsonmethod (Function_t F, Float_t A, Float_T B)
{
// Implementation of the Simpson method for segment [A, B]
}
Float_t IntegraateWithSimpsonMethod (Function_t F, Float_t A, Float_T B)
{
IF (B & LT; a) Throw ...;
// Option with uniform division on segments.
Const STD :: Size_t steps = 20;
Assert (Steps & GT; 1);
Const float_t singlestep = (b - a) / steps;
Float_t Result = 0;
For (STD :: SIZE_T i = 0; i & lt; (steps - 1); ++ i)
{
const float_t Locala = I * SingleSep;
const float_t localb = (i + 1) * singlestep;
Result + = PartintegraateWithSimpsonMethod (F, Locala, Localb);
}
RETURN RESULT;
}
```

**Your task is now – to realize the simpson method itself and understand how to correctly transmit the original function through some FUNCTION_T , and that is a matter of technology. **

By the way, *“to think” *– determine what the shortcomings of the proposed code and what could be done better.

## Answer 2, AUTHORITY 60%

```
double simpsonmethod (double a, double b, unsigned n, double (* f) (double x)) {
Double H = (b - a) / n;
Double Sum = 0;
Double x0 = a;
Double x1 = a + h;
For (unsigned i = 0; i & lt; = n-1; i ++) {
Sum + = f (x0) + 4 * f (x0 + h / 2) + f (x1);
x0 + = h;
x1 + = h;
}
RETURN (H / 6) * SUM;
}
```

## Answer 3, Authority 60%

In response @NullPTR there is a constant touch of the same data, only therefore I offer my option (I wrote a long time ago, the integral with a given error …)

```
double simpson (double a, double b, double eps, double (* f) (Double))
{
double n = 4.;
Double Sum1 = 0., Sum2 = 0.;
Double X, H;
Double index1, index2;
unsigned int i;
Double Func;
For (;;) {// In principle, in case of divergence, it is better to put a limiter for the number of iterations ...
h = (b-a) / n;
Sum1 = Sum2 = - (F (A) + F (B));
index1 = index2 = 4.;
i = 0;
For (x = a; x & lt; = b + h / 2.; x + = h) {
Sum1 + = (index1 = 6.-index1) * (FUNC = F (X));
if (I ++% 2 == 0) {
Sum2 + = (index2 = 6.-index2) * FUNC;
};
};
if (Fabs (Sum1-2. * Sum2) / Sum1) & lt; = EPS) RETURN (H * SUM1) /3.+h* (2. * SUM2-SUM1) / 45.; ELSE N * = 2;
};
Return (H * Sum1) / 3;
};
```