Number divided by a divisor greater than it returns zero?

3

I went to do a calculation in Python 2.7 and I was scared to see the result:

 val = 1 / 16
 print(val); # 0

Example on IDEONE

That is, when we make a division where the number divided is less than the divisor, the result returned is zero.

  • How do I get the result in float ?

  • Why does Python behave this way?

asked by anonymous 14.04.2017 / 18:37

2 answers

8

Division of integers, returns integer. Make one of them type float :

val = float(1) / 16
print(val);

#saida: 0.0625

Or force the change of the behavior of the / operator so that it is equal to python3.x :

from __future__ import division

val = 1/16
print(val);

#saida: 0.0625
14.04.2017 / 18:54
5

In almost every language the division of integers results in an integer. To ensure that the operation results in a floating-point number, you must have at least one of the operands as float , so you need to place a decimal point in one of them. This is strong typing .

val = 1.0 / 16
print(val); # 0

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

    
14.04.2017 / 18:41