If you divide 2 integers, you will get the result with a truncated integer (i.e. any fractional part of the result will be discarded), therefore
1 / 3
gives you:
0
To avoid this problem, at least one of the operands must be floating. for example, 1.0 / 3 or 1 / 3.0 or (of course) 1.0 / 3.0 will avoid whole truncation . This behavior is not unique to Python.
( Edit : as @Ivc mentioned in the helpful comment below, if one of the integer operands is negative, the result is floor () 'ed - see this article for the reason for this).
In addition, there may be some confusion in the internal and external representation of the number. A number is what it is, but we can determine how it was displayed.
You can control the appearance using formatting instructions. For example, a number can be displayed with 5 digits after the decimal point as follows:
n = 1/3.0 print '%.5f' %n 0.33333
To get 15 digits after a decimal number.
print '%.15f' %n 0.333333333333333
Finally, there is a โnew and improvedโ way to format strings / numbers using the .format() function, which will probably be around a lot longer than the % format shown above. An example is:
print 'the number is {:.2}'.format(1.0/3.0)
will provide you with:
the number is 0.33
Levon
source share