Is there a difference between an int of 5 and a fl

2019-08-24 20:45发布

I am confused on whether there is or is not any difference between and int of 5 and a float of 5.0, besides the float having a decimal.

4条回答
2楼-- · 2019-08-24 21:13

They are different types.

>>> type(5)
<type 'int'>
>>> type(5.0)
<type 'float'>

Internally, they are stored differently.

查看更多
叼着烟拽天下
3楼-- · 2019-08-24 21:13

5 and 5.0 are different objects in python so 5 is 5.0 is False

But in most cases they behave the same like 5 == 5.0 is True

查看更多
劫难
4楼-- · 2019-08-24 21:26

They are different data types:

 type(5)     # int
 type(5.0)   # float

And therefore they are not, strictly speaking, the same.

However, they are equal:

5 == 5.0     # true
查看更多
Luminary・发光体
5楼-- · 2019-08-24 21:40

This question is already answered: they have different type.
But what does that mean?

One must think in term of object: they are somehow objects of different classes, and the class dictates the object behavior.

Thus they will behave differently.

It's easier to grasp such things when you are in a pure object oriented language like in Smalltalk, because you clearly can browse the Float and Integer classes and learn how they might differ thru their implementation. In Python, it's more complex because the computation model is multi-layer with notions of types, operators, function, and this complexity is somehow obscuring the basic object oriented principles. But from behavioural point of view, it ends up being the same: Python : terminology 'class' VS 'type'

So what are these differences of Behavior?
They are thin because we make our best effort to have uniform and unsurprising arithmetic (including mixed arithmetic) behavior matching the laws of mathematics, whatever the programming language.

Floating point behaves differently because they keep a limited number of significand bits. It's a necessary trade-off for keeping computations simple and fast. Small integers require few significand bits, so they will behave mostly the same than floating point. But when growing larger, they won't. Here is an arithmetic example:

print(5.0**3 == 5**3)
print(5.0**23 == 5**23)

The former expression will print True, the later False... Because 5^23 requires 54bits to be represented and Python VM will in most case depend on IEEE754 double floating point which provide only 53 bits significand.

查看更多
登录 后发表回答