Lostsoul
Lostsoul

Reputation: 26037

Getting decimals from python math function?

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

Upvotes: 1

Views: 1527

Answers (3)

Mark Byers
Mark Byers

Reputation: 838896

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.

Upvotes: 4

David Heffernan
David Heffernan

Reputation: 613382

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)

Upvotes: 2

tekknolagi
tekknolagi

Reputation: 11022

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

Upvotes: 2

Related Questions