Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python floating point precision sum

I have the following array in python

n = [565387674.45, 321772103.48,321772103.48, 214514735.66,214514735.65, 357524559.41]

if I sum all these elements, I get this:

sum(n)
1995485912.1300004

But, this sum should be:

1995485912.13

In this way, I know about floating point "error". I already used the isclose() function from numpy to check the corrected value, but how much is this limit? Is there any way to reduce this "error"?

The main issue here is that the error propagates to other operations, for example, the below assertion must be true:

assert (sum(n) - 1995485911) ** 100 - (1995485912.13 - 1995485911) ** 100 == 0.

like image 603
André Davys Carvalho Avatar asked Jul 12 '18 18:07

André Davys Carvalho


People also ask

Can you use sum on floats in Python?

Additionally, you can use sum() with any other numeric Python types, such as float , complex , decimal.

Why are floating point calculations so inaccurate in Python?

It's a problem caused when the internal representation of floating-point numbers, which uses a fixed number of binary digits to represent a decimal number. It is difficult to represent some decimal number in binary, so in many cases, it leads to small roundoff errors.


1 Answers

This is problem with floating point numbers. One solution is having them represented in string form and using decimal module:

n = ['565387674.45', '321772103.48', '321772103.48', '214514735.66', '214514735.65',
     '357524559.41']

from decimal import Decimal

s = sum(Decimal(i) for i in n)

print(s)

Prints:

1995485912.13

like image 80
Andrej Kesely Avatar answered Nov 08 '22 00:11

Andrej Kesely