3 ms·
If you add together many numbers, do it in ascending order, numbers with smallest absolute values first. Comparing floats is tricky. Use either epsilon, epsil
by nabla9 9y ago
If you add together many numbers, do it in ascending order, numbers with smallest absolute values first.
Comparing floats is tricky. Use either epsilon, epsilon with relative error or ULP's (all are tricky)
- jjgreen 9y agoThat costs a sort, better to use the Kahan summation formula https://en.wikipedia.org/wiki/Kahan_summation_algorithm https://en.wikipedia.org/wiki/Kahan_summation_algorithm
- Retric 9y agoLook at the accuracy comment, it's faster but less accurate than sorting first.
- srean 9y agoIf the numbers happen to be >=0, one could do a little better by merging in Huffman order. In big 'O' the time complexity is the same.