Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 2 in the following?

c = a / b 
like image 270
Nathan Fellman Avatar asked Aug 12 '09 18:08

Nathan Fellman


People also ask

How do you fix a floating point division by zero?

Floating point error means that there is a division by a zero value in your code. It can be a variable, input, or a function in use that returns zero value. You need to identify this variable/input/function and make sure that the returned value is not zero.

How do you force floating point division?

To divide float values in Python, use the / operator. The Division operator / takes two parameters and returns the float division. Float division produces a floating-point conjecture of the result of a division. If you are working with Python 3 and you need to perform a float division, then use the division operator.

How do you divide without rounding?

First, use division or long division ignoring the decimal point. Next, put the decimal point in the same spot as the dividend (the number being divided). Note that the dividend is the number being divided so it goes into our division box and the divisor is the number doing the dividing.

Does division always result in a float?

Adding subtracting or multiplying two ints always yields an int result, but division is different. The result of division is always a float value, even if the division comes out even.


1 Answers

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 
like image 84
Michael Fairley Avatar answered Sep 28 '22 04:09

Michael Fairley