1

I'm a bit new to python and can't seem to figure out what I'm doing wrong.

a = 9
b = 13
print ((a-b)/a)
-1

But on my calculator, the correct answer is -0.444444444 (meaning 'a' is about 45% lower than 'b'). How can I get a few decimals to show up?

I tried

print Decimal((a-b)/a)
print float((a-b)/a)

both with the same result. it works if I make a = 9.0 but I wanted to see if there was anything I can do without changing the variables.

I'm sure this is super easy but I'm not sure what to try. Any suggestions?

Thanks

Lostsoul
  • 25,013
  • 48
  • 144
  • 239
  • 2
    This changes in Python 3. See http://stackoverflow.com/questions/1267869/how-can-i-force-division-to-be-floating-point-in-python – Nathan Oct 15 '11 at 21:40

3 Answers3

4

Try converting one (or both) of the arguments to a float, rather than the result:

print ((a-b)/float(a))

Or just upgrade to Python 3 where this behaviour has been fixed:

>>> a = 9
>>> b = 13
>>> print ((a-b)/a)
-0.4444444444444444

By the way, if you want integer division in Python 3.x you can use // instead of /. See the PEP about this change if you are interested.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 4
    If you're on Python 2.x, you can use the `from __future__ import division` statement at the beginning of your module to have the `/` operator perform float division and the `//` operator perform integer division. – Thomas Orozco Oct 15 '11 at 21:25
2

You need to specify that you want to operate on floating point numbers.

For example: 3.0/4.0 or just 3.0/4 will give you floating point. Right now it's just performing integer operations.

EDIT: you could use float(3)/4 too

tekknolagi
  • 10,663
  • 24
  • 75
  • 119
2

You are performing division on two integer operands and in Python 2.x this means integer division. That is, the result is an integer.

You need what is known as floating point division. To force this you just need at least one of the operands to the division to be a float. For example:

print ((a-b)/float(a))

or

print (float(a-b)/a)
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490