Tuesday, 27 March 2018

python - How can I force division to be floating point? Division keeps rounding down to 0?



I have two integer values a and b, but I need their ratio in floating point. I know that a < b and I want to calculate a / b, so if I use integer division I'll always get 0 with a remainder of a.




How can I force c to be a floating point number in Python in the following?



c = a / b

Answer



In Python 2, division of two ints produces an int. In Python 3, it produces a float. We can get the new behaviour by importing from __future__.



>>> from __future__ import division
>>> a = 4

>>> b = 6
>>> c = a / b
>>> c
0.66666666666666663

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...