TheAlgorithms-C/numerical_methods/simpsons_1-3rd rule.c

41 lines
736 B
C
Raw Normal View History

2020-04-08 02:31:29 +03:00
#include <stdio.h>
#include <math.h>
2018-10-02 02:31:05 +03:00
2020-04-08 02:31:29 +03:00
float f(float x)
2016-10-14 06:54:46 +03:00
{
2020-04-08 02:31:29 +03:00
return 1.0 + x * x * x; //This is the expresion of the function to integrate?
2016-10-14 06:54:46 +03:00
}
2019-02-11 03:27:57 +03:00
2020-04-08 02:31:29 +03:00
int main()
2016-10-14 06:54:46 +03:00
{
2020-04-08 02:31:29 +03:00
int i, n;
float a, b, h, x, s2, s3, sum, integral;
2018-10-02 02:31:05 +03:00
printf("enter the lower limit of the integration:");
2020-04-08 02:31:29 +03:00
scanf("%f", &a);
2018-10-02 02:31:05 +03:00
printf("enter the upper limit of the integration:");
2020-04-08 02:31:29 +03:00
scanf("%f", &b);
2018-10-02 02:31:05 +03:00
printf("enter the number of intervals:");
2020-04-08 02:31:29 +03:00
scanf("%d", &n);
h = (b - a) / n;
sum = f(a) + f(b);
s2 = s3 = 0.0;
2019-02-11 03:27:57 +03:00
2020-04-08 02:31:29 +03:00
for (i = 1; i < n; i += 3)
2016-10-14 06:54:46 +03:00
{
2020-04-08 02:31:29 +03:00
x = a + i * h;
s3 = s3 + f(x) + f(x + h);
2016-10-14 06:54:46 +03:00
}
2019-02-11 03:27:57 +03:00
2020-04-08 02:31:29 +03:00
for (i = 3; i < n; i += 3)
2016-10-14 06:54:46 +03:00
{
2020-04-08 02:31:29 +03:00
x = a + i * h;
s2 = s2 + f(x);
2016-10-14 06:54:46 +03:00
}
2020-04-08 02:31:29 +03:00
integral = (h / 3.0) * (sum + 2 * s2 + 4 * s3);
printf("\nValue of the integral = %9.4f\n", integral);
2018-10-02 02:31:05 +03:00
return 0;
2016-10-14 06:54:46 +03:00
}