1

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?

Viveran
  • 83
  • 1
  • 14

3 Answers3

2

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
BallpointBen
  • 9,406
  • 1
  • 32
  • 62
  • 1
    "*not sure why*": it's the difference between `str()` and `repr()` – cdarke Apr 16 '16 at 07:54
  • Thanks. There is only a slight difference between actual intent of the question and your answer. However, this issue happens in JAVA, too. – Viveran Apr 17 '16 at 09:32
0

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.

cdarke
  • 42,728
  • 8
  • 80
  • 84
-2

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).

Community
  • 1
  • 1
Amit Gold
  • 727
  • 7
  • 22