Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

c - Is it a good idea to use IEEE754 floating point NaN for values which are not set?

Is it a good idea to use IEEE754 floating point NaN (not-a-number) for values which are undefined for non-mathematical reasons?

In our case they are not yet set because the values have not been received from some other device. The context is an embedded system using IEC1131 REAL32 values. Edit: The programming language is C, so we would most likely use NAN and isnanf(x), which are from C99. Though we may need some extra contortions to get these into our OS compatibility layer.

The default in programming languages seems to be to initialize floating point variables with positive zero, whose internal representation is all zeros. That is not usable for us, because 0 is in the range of valid values.

It seems like a clean solution to use NaN, but maybe it is more hassle than it is worth and we should pick some other value?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just noticed this question.

This is one of the uses of NaNs that the IEEE 754 committee has in mind (I was a committee member). The propagation rules for NaNs in arithmetic make this very attractive, because if you have a result from a long sequence of calculations that involve some initialized data, you will not mistake the result for a valid result. It can also make tracing back through your calculations to find where you are using the initialized data much more straightforward.

That said, there are a few pitfalls that are outside of the 754 committee's control: as others have noted, not all hardware supports NaN values at speed, which can result in performance hazards. Fortunately, one does not often do a lot of operations on initialized data in a performance-critical setting.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...