python中inf_如何将Python除以-0.0和0.0分别导致-Inf和Inf?

I have a situation where it is reasonable to have a division by 0.0 or by -0.0 where I would expect to see +Inf and -Inf, respectively, as results. It seems that Python enjoys throwing a

ZeroDivisionError: float division by zero

in either case. Obviously, I figured that I could simply wrap this with a test for 0.0. However, I can't find a way to distinguish between +0.0 and -0.0. (FYI you can easily get a -0.0 by typing it or via common calculations such as -1.0 * 0.0).

IEEE handles this all very nicely, but Python seems to take pains to hide the well thought out IEEE behavior. In fact, the fact that 0.0 == -0.0 is actually an IEEE feature so Python's behavior seriously breaks things. It works perfectly well in C, Java, Tcl, and even JavaScript.

Suggestions?

解决方案from math import copysign

def divide(numerator, denominator):

if denominator == 0.0:

return copysign(float('inf'), denominator)

return numerator / denominator

>>> divide(1, -0.0)

-inf

>>> divide(1, 0)

inf

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值