Sum of a floating-point array consisting of large and small elements

I was asked this question during a java interview: I needed to find out the sum of the elements in a float array. The elements, however, are made up of very large and very small numbers, the question is, how can I guarantee the accuracy of the summary?

I assume that this requires some decent understanding of the implementation of Float in Java, which I, unfortunately, do not have, or is this a reasonable question?

+3
source share
4 answers

, . () , . , Kahan.

+2

BigDecimal. .

, ​​:

public BigDecimal sum(float[] floats) {
    BigDecimal sum = BigDecimal.ZERO;

    for (float aFloat : floats) {
        sum = sum.add(new BigDecimal(aFloat));
    }

    return sum;
}
+1

, BigDecimals .

-2
-2

All Articles