python 键盘输入负数,python中的负数为零

[Python 3.1]

I encountered negative zero in output from python; it's created for example as follows:

k = 0.0

print(-k)

The output will be -0.0.

However, when I compare the -k to 0.0 for equality, it yields True. Is there any difference between 0.0 and -0.0 (I don't care that they presumably have different internal representation; I only care about their behavior in a program.) Is there any hidden traps I should be aware of?

解决方案

Basically IEEE does actually define a negative zero

And by this definition for all purposes :

-0.0 == +0.0 == 0

I agree with aaronasterling that -0.0 and +0.0 are different objects. Making them equal (equality operator) makes sure that subtle bugs are not introduced in the code.

Think of a * b == c * d

>>> a = 3.4

>>> b =4.4

>>> c = -0.0

>>> d = +0.0

>>> a*c

-0.0

>>> b*d

0.0

>>> a*c == b*d

True

>>>

[Edit: More info based on comments]

When i said for all practical purposes, I had chosen the word rather hastily. I meant standard equality comparison.

I would add more information and references in this regard:

(1) As the reference says, the IEEE standard defines comparison so that +0 = -0, rather than -0 < +0. Although it would be possible always to ignore the sign of zero, the IEEE standard does not do so. When a multiplication or division involves a signed zero, the usual sign rules apply in computing the sign of the answer.

Operations like divmod, atan2 exhibits this behavior. In fact, atan2 complies with the IEEE definition as does the underlying "C" lib. See reference #2 for definition.

>>> divmod(-0.0,100)

(-0.0, 0.0)

>>> divmod(+0.0,100)

(0.0, 0.0)

>>> math.atan2(0.0, 0.0) == math.atan2(-0.0, 0.0)

True

>>> math.atan2(0.0, -0.0) == math.atan2(-0.0, -0.0)

False

One way is to find out through the documentation, if the implementation complies with IEEE behavior . It also seems from the discussion that there are subtle platform variations too.

How ever this aspect(IEEE definition compliance) has not been respected every where. See the rejection of PEP 754 (#3) due to disinterest! I am not sure if this was picked up later.

references :

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值