Python2 math.fsum not accurate?

I am using the python2 math module to calculate the sums using fsum. I understand that 0.1 cannot usually be stored in binary. As far as I understand, math.fsum should fix this.

import math
math.fsum([0.0, 0.1])
#0.1
math.fsum([0.1, 0.1])
#0.2
math.fsum([0.2, 0.1])
#0.30000000000000004
math.fsum([0.3, 0.1])
#0.4
math.fsum([0.4, 0.1])
#0.5

So math.fsum ([0.2, 0.1]) == 0.3 will be False. Should it be like that? Am I doing something wrong?

How can I get 0.2 + 0.1 == 0.3 to be true?

+4
source share
2 answers

You do not understand what is doing math.fsum. It calculates the most accurate possible sum of these inputs (i.e., the closest accurately represented value to the exact mathematical sum of the inputs). It does not magically replace its inputs with the numbers you originally thought.

math.fsum , 0.1000000000000000055511151231257827021181583404541015625 0.200000000000000011102230246251565404236316680908203125 (, , , , , , Python). 0.3000000000000000166533453693773481063544750213623046875, IEEE 754 64 - 0.3000000000000000444089209850062616169452667236328125, .

math.fsum , 0.1 0.2, , : , .

, , math.fsum. math.fsum , .

+6

float. float.

, , :

:

def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
    return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

:

float Python?

:

http://0.30000000000000004.com/

0,1 + 0,2 0,3 .

+1

Source: https://habr.com/ru/post/1623226/


All Articles