# Float angle != angle什么时候为true？

[TOC]

if (angle != angle)
{
return XMQuaternionIdentity();
}

## 源代码

DirectX::XMVECTOR SimStarMan::QuaternionFromToRotation(const XMVECTOR& from, const XMVECTOR& to)
{
XMVECTOR quatRet;
XMVECTOR axis, fromN, toN;
float angle;
fromN = XMVector3Normalize(from);
toN = XMVector3Normalize(to);
const XMVECTOR epsilon = XMLoadFloat3(&XMFLOAT3(0.00001f, 0.00001f, 0.00001f));

if (XMVector3NearEqual(fromN, toN, epsilon))
{
return XMQuaternionIdentity();
}
axis = XMVector3Cross(fromN, toN);
axis = XMVector3Normalize(axis);
angle = acosf(XMVectorGetX(XMVector3Dot(fromN, toN)));
if (angle != angle)
{
return XMQuaternionIdentity();
}
quatRet = XMQuaternionRotationAxis(axis, angle);
quatRet = XMQuaternionNormalize(quatRet);
return quatRet;
}

## NAN

float a = acos(2);
cout << "a = " << a << endl;    // a = nan
cout << (a != a) << endl;         // 1

## 向量可能有问题

For a vector of length 0, this function returns a zero vector. For a vector with infinite length, it returns a vector of QNaN.


## acosf会出现Nan的情况

If no errors occur, the arc cosine of arg (arccos(arg)) in the range [0 ; π], is returned.

If a domain error occurs, an implementation-defined value is returned (NaN where supported).

If a range error occurs due to underflow, the correct result (after rounding) is returned.

## 如何写更优雅？

This answer should be updated since std::isnan is now part of the C++11 standard and support has spread out. std::isnan was implemented in Visual Studio starting with Visual Studio 2013.


// old
angle ! = angle
// new
std::isnan(angle)

## NaN定义

IEEE 754 floating point numbers can represent positive or negative infinity, and NaN (not a number).


#### 小结：

• NaN在运算中得结果始终都是NaN，不像infinity有可能算出来一个正常值，比如 4/∞ = 0
• NaN的浮点数IEEE表示是一个范围，节码都是1，所以尾数表示的范围都是NaN
Positive infinity is represented by the bit pattern X'7F80 0000'.
Negative infinity is represented by the bit pattern X'FF80 0000'.
A signaling NaN (NANS) is represented by any bit pattern between X'7F80 0001' and X'7FBF FFFF' or between X'FF80 0001' and X'FFBF FFFF'.
A quiet NaN (NANQ) is represented by any bit pattern between X'7FC0 0000' and X'7FFF FFFF' or between X'FFC0 0000' and X'FFFF FFFF'.

31
|
| 30    23 22                    0
| |      | |                     |
-----+-+------+-+---------------------+
qnan 0 11111111 10000000000000000000000
snan 0 11111111 01000000000000000000000
inf 0 11111111 00000000000000000000000
-inf 1 11111111 00000000000000000000000
-----+-+------+-+---------------------+
| |      | |                     |
| +------+ +---------------------+
|    |               |
|    v               v
| exponent        fraction
|
v
sign