开发者

Dealing with special floating point values in Python

I am writing a simple app that takes a bunch of numerical inputs and calculates a set of results. (The app is in PyGTK but I don't think that's relevant.)

My problem is that if I want to just have NaN's and Inf's propagated through, then in every calculation I need to do something like:

# At the top of the module
nan = float("nan")
inf = float("inf")

try:
  res = (a + b) / (0.1*c + d)
except ZeroDivisionError:
  # replicate every little subtlety of IEEE 754 here
except OverflowError:
  # replicate every little subtlety of IEEE 754 here again

...or, of course, pre-empt it for every calculation:

numerator = a + b
denominator = 0.1*c + d

if denominator == 0:
  # etc
elif math.isnan(numerator):
  # *sigh*

How can I deal with this sanely in Python 2.6? Do I really need to install a massive 3rd-party module (numpy, scipy) on every target machine just to do IEEE 754 开发者_Go百科arithmetic? Or is there a simpler way?


No, Python's built-in math raises exceptions for errors rather than returning them as NaN and INF. You'll need to use a library or your own code if you don't want this behavior.

(Thought I'd give the simple answer, since too many questions where the answer is "sorry, no" simply don't get answered.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜