Tuesday 22 January 2019

Adding Floating Point Numbers in Python

I've recently been doing some work in Python and noticed that it can't add floating point numbers correctly! I Googled it and found that this isn't a bug, it's expected because the C code underneath converts the floating point into a fraction to add the numbers and not all numbers can be converted to fractions and vice-versa!!

It may be expected but it is definitely in no way correct.

With my limited knowledge I've created this function to convert the floating point numbers to decimals, perform the addition, then convert back to floating point.

def add_floats(v): multiplier = 1 for i in v: multiplier = max(len(str(i)) - str(i).find('.'), multiplier) multiplier = 10**multiplier total = 0 for i in v: total += (i * multiplier) total = total / multiplier return total x = float('1.41') y = float('1.4') z = x+y print(x+y) print(add_floats([x, y]))
Output:

2.8099999999999996 2.81
My Python knowledge is limited, so if anyone wishes to improve this, please let me know.