-
Notifications
You must be signed in to change notification settings - Fork 7
/
romberg.c
122 lines (97 loc) · 2.21 KB
/
romberg.c
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
#include <math.h>
#include <stdlib.h>
#include <limits.h>
#include <assert.h>
#include "floattype.h" /* because some systems don't define FLT_MAX */
#include "romberg.h"
#define MAXLEV 13
/*
** Romberg integrator for an open interval.
*/
double
dRombergO(void *CTX,double (*func)(void *, double),double a,double b,
double eps)
{
double tllnew;
double tll;
double tlk[MAXLEV+1];
int n = 1;
int nsamples = 1;
tlk[0] = tllnew = (b-a)*(*func)(CTX, 0.5*(b+a));
if(a == b) return tllnew;
tll = FLT_MAX;
while((fabs((tllnew-tll)/tllnew) > eps) && (n < MAXLEV)) {
/*
* midpoint rule.
*/
double deltax;
double tlktmp;
int i;
nsamples *= 3;
deltax = (b-a)/nsamples;
tlktmp = tlk[0];
tlk[0] = tlk[0]/3.0;
for(i=0;i<nsamples/3;i++) {
tlk[0] += deltax*(*func)(CTX,a + (3*i + 0.5)*deltax);
tlk[0] += deltax*(*func)(CTX,a + (3*i + 2.5)*deltax);
}
/*
* Romberg extrapolation.
*/
for(i=0;i<n;i++) {
double tlknew = (pow(9.0, i+1.)*tlk[i] - tlktmp)
/(pow(9.0, i+1.) - 1.0);
if(i+1 < n)
tlktmp = tlk[i+1];
tlk[i+1] = tlknew;
}
tll = tllnew;
tllnew = tlk[n];
n++;
}
assert((fabs((tllnew-tll)/(tllnew+eps)) < eps));
return tllnew;
}
double
dRombergC(void *CTX,double (*func)(void *, double),double a,double b,
double eps)
{
double tllnew;
double tll;
double tlk[MAXLEV+1];
int n = 1;
int nsamples = 1;
tlk[0] = tllnew = (b-a)*0.5*((*func)(CTX, b) + (*func)(CTX, a));
if(a == b) return tllnew;
if(tllnew == 0.0) return tllnew;
tll = FLT_MAX;
while((fabs((tllnew-tll)/tllnew) > eps) && (n < MAXLEV)) {
/*
* midpoint rule.
*/
double deltax;
double tlktmp;
int i;
nsamples *= 2;
deltax = (b-a)/nsamples;
tlktmp = tlk[0];
tlk[0] = tlk[0]/2.0;
for(i=0;i<nsamples/2;i++) {
tlk[0] += deltax*(*func)(CTX,a + (2*i + 1.0)*deltax);
}
/*
* Romberg extrapolation.
*/
for(i=0;i<n;i++) {
double tlknew = (pow(4.0, i+1.)*tlk[i] - tlktmp)
/(pow(4.0, i+1.) - 1.0);
tlktmp = tlk[i+1];
tlk[i+1] = tlknew;
}
tll = tllnew;
tllnew = tlk[n];
n++;
}
assert((fabs((tllnew-tll)/tllnew) < eps));
return tllnew;
}