Viveran
Viveran

Reputation: 83

Double and Float Precision

a = 2.3

b = a*100

print b

output : 230.0

print 2.3*100

output: 229.99999999999997

What it seems like that Double and Float multiplication are done differently. Is it?

What is the explanation for the above behaviour?

Upvotes: 1

Views: 1117

Answers (3)

cdarke
cdarke

Reputation: 44354

I am assuming you are using old python 2 because of your print statements. When I run the code you give I get the same result, for both print statements:

Python 2.7.10 (default, Jul 14 2015, 19:46:27) 
>>> a = 2.3
>>> b = a*100
>>> print b
230.0
>>> print 2.3*100
230.0

I suspect you are using interactive python. This is a feature of conversion from floating-point to strings:

Python 2.7.10 (default, Jul 14 2015, 19:46:27) 
>>> 2.3*100
229.99999999999997
>>> print 2.3*100
230.0
>>> str(2.3*100)
'230.0'
>>> repr(2.3*100)
'229.99999999999997'

This illustrates the difference between str, which print uses, and repr, which interactive python uses.

Upvotes: 0

Amit Gold
Amit Gold

Reputation: 767

A quick google search gave me this.

Basically, floats are represented in bits(0-1), similar to how numbers that we know are represented with 0-9. A lot of numbers cannot represented accurately that way, similar to how we cannot represent accurately 1/3 in decimal(the regular 0-9).

Upvotes: -2

BallpointBen
BallpointBen

Reputation: 13750

First, Python only has a single type for floating point numbers, which is float; there is no double type.

Now, I'm not sure why, but your issue seems to come down to the use of print.

>>> 2.3*100
229.99999999999997
>>> print 2.3*100
230.0

That was Python 2.7.10. Interestingly, this does not occur in 3.5.1:

>>> 2.3*100
229.99999999999997
>>> print(2.3*100)
229.99999999999997

Upvotes: 2

Related Questions