Wednesday 22 November 2017

Python: Division by Larger Number

itemprop="text">




print
1/50


results to a
rounded zero: 0




print
float(1/50)


once again
returns zero but as a float.



What syntax I
should be using to get a right result (0.02) using only stock
modules.



Answer




This
line:



print
float(1/50)



Performs
an integer division of 1/50, and then casts it to a float. This is the wrong order,
since the integer division has already lost the fractional
value.



You need to cast to a float
first, before the division, in one of these
ways:



float(1)/50
1./50


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...