-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinteglib.cc
140 lines (131 loc) · 2.71 KB
/
integlib.cc
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
//libreria degli algoritmi per l'integrazione
#include "prototypes.h"
double PoorEuler(double (*fz)(double x),double inf,double sup,int &N,int &count)
{
double ak,bk,Ik=0,Iprev,fzak;
double dx=(sup-inf)/N;
do
{
ak=inf;
bk=ak+dx;
Iprev=Ik;
Ik=0.;
for(int i=0;i<=N;i++)
{
fzak=fz(ak);
Ik+=(bk-ak)*fzak;
ak=bk;
bk+=dx;
}
} while(fabs(Ik-Iprev)>1.e-9);
return Ik;
}
double MidPoint(double (*fz)(double x),double inf,double sup,int &N,int &count)
{
double ak,bk,Ik=0,Iprev,ck,fzck;
double dx=(sup-inf)/N;
do
{
ak=inf;
bk=ak+dx;
Iprev=Ik;
Ik=0.;
for(int i=0;i<=N;i++)
{
ck=0.5*(ak+bk);
fzck=fz(ck);
Ik+=(bk-ak)*fzck;
ak=bk;
bk+=dx;
}
} while(fabs(Ik-Iprev)>1.e-9);
return Ik;
}
double Trapezoidal(double (*fz)(double x),double inf,double sup,int &N,int &count)
{
double ak,bk,fzak,fzbk,Ik=0,Iprev;
double dx=(sup-inf)/N;
do
{
ak=inf;
bk=ak+dx;
fzak=fz(ak);
fzbk=fz(bk);
Iprev=Ik;
Ik=0.;
for(int i=0;i<=N;i++)
{
Ik+=0.5*(bk-ak)*(fzak+fzbk);
ak=bk;
bk+=dx;
fzak=fzbk;
fzbk=fz(bk);
}//end for
N*=2;
count++;
} while(fabs(Ik-Iprev)>1.e-9);
return Ik;
}
double Simpson(double (*fz)(double x),double inf,double sup,int &N,int &count)
{
double ak,bk,fzak,fzbk,ck,fzck,Ik=0,Iprev;
do{
double dx=(sup-inf)/N;
ak=inf;
bk=ak+dx;
Iprev=Ik;
Ik=0.;
/* for(int i=1;i<=N;i++)
{
fzak=fz(ak);
fzbk=fz(bk);
ck=0.5*(ak+bk);
fzck=fz(ck);
Ik+=((bk-ak)/6)*(fzak+4*fzck+fzbk);
ak=bk;
bk+=dx;
}*/
//metodo più efficiente:
int coeff=4;
Ik=fz(inf)+fz(sup);
for(int i=1;i<=N-1;i++)
{
Ik+=fz(inf+i*dx)*coeff;
coeff=6-coeff;
}
Ik*=(bk-ak)/3.;
N*=2;
count++;
}while(fabs(Ik-Iprev)>1.e-9);
return Ik;
}
double GaussLegendre(double (*fz)(double x),double inf,double sup,int &N,int &count)
{
static const int n=8;//grado del polinomio
double xi[n]={-0.1834346424956498,0.1834346424956498,-0.5255324099163290,0.5255324099163290,-0.7966664774136267,0.7966664774136267,-0.9602898564975363,0.9602898564975363};
double wi[n]={0.3626837833783620,0.3626837833783620,0.3137066458778873,0.3137066458778873,0.2223810344533745,0.2223810344533745,0.1012285362903763,0.1012285362903763};
double I=0.,Ik,Iprev,ak,bk,ck;
do{
double delta=(sup-inf)/(double)N;
ak=inf;
bk=inf+delta;
Iprev=I;
I=0.;
for(int ii=1;ii<=N;ii++)
{
Ik=0.;
for(int i=0;i<8;i++)
{
ck=0.5*(bk-ak)*xi[i]+0.5*(ak+bk);
Ik+=wi[i]*fz(ck);
}//end i for
Ik*=0.5*(bk-ak);
I+=Ik;
ak=bk;
bk+=delta;
}//end ii for
N*=2;
count++;
}while(fabs(I-Iprev)>1.e-9);
return I;
}