Tuesday, 4 October 2016

numbers - Why doesn't this division work in Python?

In Python 2.x, division works like it does in C-like languages: if both arguments are integers, the result is truncated to an integer, so 29/1009 is 0. 0 as a float is 0.0. To fix it, cast to a float before dividing:


print str(float(numerator)/denominator)

In Python 3.x, the division acts more naturally, so you'll get the correct mathematical result (within floating-point error).

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...