1
2
3
4
| Sn = 1, q, q^2, q^3 ... q^n
q * Sn = q, q^2, q^3 ... q^n, q^n+1
Sn - q * Sn = 1 - q^n+1
Sn = (1 - q^n+1) / (1 - q) 其中 q != 1
|
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
| public class KahanSummation {
private static float kahanSum(float... fa) {
float sum = 0.0f;
float c = 0.0f;
for (float f : fa) {
float y = f - c;
float t = sum + y;
c = (t - sum) - y;
sum = t;
}
return sum;
}
private static float epsilon() {
float eps = 1.0f;
while (1.0f + eps != 1.0f) eps /= 2.0f;
return eps;
}
public static void main(String[] args) {
float a = 1.0f;
float b = epsilon();
float c = -b;
System.out.println("Epsilon = " + b);
System.out.println("(a + b) + c = " + ((a + b) + c));
System.out.println("Kahan sum = " + kahanSum(a, b, c));
}
}
|