Juxhin
Juxhin

Reputation: 5600

Why is Python 2.X division not working as intended even after using float

So after a while of reading through some of my code I kept getting this weird behavior that I simply couldn't get off.

After a while of looking I noticed that the following equation:

>>> print 425 / (469 / 100) 

Would return 106 instead of ~90. I kept on reading about such behavior in Python and explicitly used float to hopefully help with the accuracy a little bit.

>>> print 425 / float(469 / 100)

Which would now return 106.25 which was not all too helpful. After breaking this up further I simply tried the following:

>>> print float(469 / 100)

Which to my surprise returned 4.0 and not even 4.1 (rounding). Something that I have encountered with Java but not with Python yet.

Even though I am explicitly using float why I am receiving such results? I don't require precise accuracy but wanted it to atleast be between 89 and 91.

This is using Python 2.7

Upvotes: 0

Views: 68

Answers (2)

saulspatz
saulspatz

Reputation: 5261

Or put

from __future__ import division

as the first line of your program. Then / is floating point division, but you'll have to use // to get ineteger divsion

>>> from __future__ import division
>>> 425 / (469 / 100)
90.61833688699359
>>> 425 // (469 // 100)
106

Upvotes: 1

chepner
chepner

Reputation: 530823

float isn't called until the division is performed; the / is not affected by the context in which it is called, only by the operands it receives. You need to convert at least one of the operands to a float, not the result. For example,

>>> print 425 / (469 / float(100))
90.618336887

Upvotes: 2

Related Questions