ЧСМ 2 лаба

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include "stdafx.h"
#include <stdio.h>
#include <math.h>
#define e 0.000001
double f(double x) {
return exp(x);
}
//метод прямоугольника
double integral1(double a, double b, int n) {
double res = 0, h = (b-a)/n;
for( int i=0;i<n;i++) {
res+=f(a+h*(i+0.5));
}
return res*=h;
}
//метод трапеций
double intergal2(double a, double b, int n) {
double res = 0, h = (b-a)/n;
for( int i=0;i<n;i++) {
double A = a+h*i, B = a+h*(i+1);
res+=(f(A)+f(B))/2;
}
return res*=h;
}
//метод Симпсона
double integral3(double a, double b, int n) {
double res = 0, h = (b-a)/n;
for( int i=0;i<n;i++) {
double A = a+h*i, B = a+h*(i+1);
res+=((B-A)/6.0) *(f(A)+4.0*f((A+B)/2.0)+f(B));
}
return res;
}
int main(void) {
double int1, int2, int3, d = 1.0;
for (int n=1;d>e;n*=2) {
d = abs((int1 = integral1(0,1,2*n)) - integral1(0,1,n))/3.0;
}
d=1.0;
for (int n=1;d>e;n*=2) {
d = abs((int2 = intergal2(0,1,2*n)) - intergal2(0,1,n))/3.0;
}
d=1.0;
for (int n=1;d>e;n*=2) {
d = abs((int3 = integral3(0,1,2*n)) - integral3(0,1,n))/15.0;
}
printf("%f\n", int1);
printf("%f\n", int2);
printf("%f\n", int3);
return 0;
}