1

When I do:

>>> x = 1
>>> y = 4
>>> x/y
0

It returns 0 instead of 0.25 because I didn't declare x or y as a float. But even when I do:

>>> x = 0.0
>>> x = 1
>>> y = 4
>>> x/y
0

It still returns 0?

How can I perform floating point division on the integers x and y without using float(x) / float(y)?

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
user3896400
  • 85
  • 1
  • 9
  • 1
    "even if i put x = 0.0 before he return 0 again" - well of course it'll give you a zero, because you put x=0.0 instead of x=1.0. – user2357112 Mar 30 '15 at 23:06
  • 1
    `0.0/some_number` should result in the floating point number `0.0` for all python implementations. Normally in these cases, I'd advise that you `from __future__ import division`, but it's hard to tell if that actually applies here... – mgilson Mar 30 '15 at 23:06
  • if i put 0.0 in declaration afte the code change the value to 1 – user3896400 Mar 30 '15 at 23:07
  • 2
    if you write `x=0.0` and then `x=1`, `x` will be an `int` and not a `float` – Julien Spronck Mar 30 '15 at 23:11
  • 2
    also, in python, you do not declare variables – Julien Spronck Mar 30 '15 at 23:12
  • 1
    Worth noting: only one of the variables needs to be a float to perform floating point division. `1. / 4` and `1 / 4.` will both yield `0.25`. – David Cain Mar 30 '15 at 23:12

1 Answers1

4

You can put:

from __future__ import division

at the top of your module. This will make the / operator behave as if it's doing float-divison by default; you can use the // operator if you still want floor-division.

tzaman
  • 46,925
  • 11
  • 90
  • 115