Kahan summation: Difference between revisions

Content added Content deleted
(→‎{{header|Kotlin}}: Updated example see https://github.com/dkandalov/rosettacode-kotlin for details)
(Added Java)
Line 918: Line 918:


See also http://keiapl.info/anec/#fuzz
See also http://keiapl.info/anec/#fuzz

=={{header|Java}}==
{{trans|Kotlin}}
As is noted in the Kotlin implementation, the JVM does not provide the desired decimal type, so the alternate implementation is provided instead.
<lang Java>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));
}
}</lang>
{{out}}
<pre>Epsilon = 5.9604645E-8
(a + b) + c = 0.99999994
Kahan sum = 1.0</pre>


=={{header|Kotlin}}==
=={{header|Kotlin}}==