Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print full precision of floating numbers [Python]

I had written the following function in which values of x,y were passed:

def check(x, y):
    print(type(x))
    print(type(y))
    print(x)
    print(y)
    if x == y:
        print "Yes"

Now when I called check(1.00000000000000001, 1.0000000000000002) it was printing:

<type 'float'>
<type 'float'>
1.0
1.0

Now from the print statements of variables x & y, it was hard for me to debug why x != y (though both were printing same values). Though I resolved it by printing x - y which gave me the difference but is there any way to modify print statement so that to know why x!=y in this particular use case without using any external print libraries and subtraction solution.

like image 988
skaul05 Avatar asked Sep 27 '18 07:09

skaul05


1 Answers

To get full precision and correct formatting do

format(2**(1/2), '.60g') 
# -> '1.4142135623730951454746218587388284504413604736328125'

and check it with

import decimal
print(decimal.Decimal.from_float(2**(1/2))
# -> '1.4142135623730951454746218587388284504413604736328125'

The g format type switchs to exponential notation when needed.

like image 180
angeldeluz777 Avatar answered Oct 26 '22 03:10

angeldeluz777