python long number data loss -


i starting python (python3) because read euler project since can handle big numbers.

now struggling quite simple problem of converting float int. why don't same result this:

num =  6008514751432349174082765599289028910605977570  print('num     {0} '.format(int(num)))  num = num / 2 print('num /2  {0} '.format(int(num)))  num = num * 2 print('num *2  {0} '.format(int(num))) 

output is:

num     6008514751432349174082765599289028910605977570  num /2  3004257375716174771611310192874715313222975488  num *2  6008514751432349543222620385749430626445950976  

you using float division, cannot handle large numbers precision, after flooring result casting int().

don't that, causes data loss. use integer (floor) division // instead:

>>> 6008514751432349174082765599289028910605977570 // 2 * 2 6008514751432349174082765599289028910605977570 

this still can lead rounding errors of course, if input value not divisible 2 without flooring:

>>> 6008514751432349174082765599289028910605977571 // 2 * 2 6008514751432349174082765599289028910605977570 

but floating point values limited in precision based on exact cpu support; see sys.float_info see exact limitations platform imposes on float numbers.

on mac, sys.float_info.dig tells me platform supports 15 digits of precision, dividing 46-digit integer number. means throw away bottom 30 digits large integer when using float division:

>>> len(str(int(6008514751432349174082765599289028910605977570 / 2) - (6008514751432349174082765599289028910605977570 // 2))) 30 

that lot of precision loss there. :-)


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -