您的位置:首页 > 编程语言 > C语言/C++

How to check for NAN / INF / IND in C++

2014-01-19 19:54 429 查看
http://studiofreya.com/c/how-to-check-for-nan-inf-ind-in-c/


How to check for NAN / INF / IND in C++

Recently we had occasional, but serious problems with some software we’re making. The problems were with invalid floating point numbers.

Once invalid (
IND
/
INF
/
NAN
)
numbers have infested your simulation, it’s very difficult to get rid of it. It’s like a viral infection. The best way to avoid invalid floating point numbers are to prevent them happening in the first place.

What happened was that invalid floating point values were introduced while calculating the angle between two vectors. The acos method
calculate the angle, and it’s domain is
[-1, 1]
. Due to rounding errors, the actual value passed to
acos
was
slightly less or slightly above the domain, which resulted in an invalid number.

The way we caught the error was to modify the vector3d-class and insert breakpoints when the expression
value != value
is
true. Only
NAN
and
IND
values
behave like that.

After the breakpoints were set, the call stack gave it all away.

Here is a sample program for detecting invalid numbers.

Output is:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: