# 最后一位上的单位值

## 例子

```#include <cmath>
#include <cstdio>
#define PI 3.14159265358979323846264338327950288419716939937510582097494459230

int main()
{
printf("%.17g (%a)\n", PI, PI);
printf("%.17g (%a)\n", std::nextafter(PI, 0.0), std::nextafter(PI, 0.0));
printf("%.17g (%a)\n", std::nextafter(PI, 4.0), std::nextafter(PI, 4.0));
}
/* Output:
3.1415926535897931 (0x1.921fb54442d18p+1)
3.1415926535897927 (0x1.921fb54442d17p+1)
3.1415926535897936 (0x1.921fb54442d19p+1)
*/
```

xIEEE 754表示时四舍五入且舍入到偶数的操作记为RN。如果ULP(x)的值小于等于1，那么RN(x + 1) > x；否则，RN(x + 1) = xRN(x + 1) = x + ULP(x)，取决于最低有效位（least significant digit）与x的指数部分。下面的Python程序展示了这个例子：

```>>> x = 1.0
>>> p = 0
>>> while x != x + 1:
...   x = x * 2
...   p = p + 1
...
>>> x
9007199254740992.0
>>> p
53
>>> x + 2 + 1
9007199254740996.0
```

## 语言支持

C语言标准库从C99开始提供了计算给定方向的下一个浮点数的函数： `nextafterf``nexttowardf`用于`float`, `nextafter``nexttoward`用于`double`, `nextafterl``nexttowardl`用于`long double`, 都在`<math.h>`中声明。[6]

Boost C++ Libraries提供了boost::math::float_next, boost::math::float_prior, boost::math::nextafterboost::math::float_advance等函数获取邻近的浮点数。 [7]boost::math::float_distance(a, b)计算两个double值之间的浮点距离。 [8]

## 参考文献

1. ^ David Goldberg: What Every Computer Scientist Should Know About Floating-Point Arithmetic, section 1.2 Relative Error and Ulps, ACM Computing Surveys, Vol 23, No 1, pp.8, March 1991.
2. ^ Higham, Nicholas. Accuracy and Stability of Numerical Algorithms (2 ed). SIAM. 2002.
3. ^ Harrison, John. A Machine-Checked Theory of Floating Point Arithmetic. [2013-07-17].
4. ^ Muller, Jean-Michel (2005-11). "On the definition of ulp(x)". INRIA Technical Report 5504. ACM Transactions on Mathematical Software, Vol. V, No. N, November 2005. Retrieved in 2012-03 from http://ljk.imag.fr/membres/Carine.Lucas/TPScilab/JMMuller/ulp-toms.pdf.
5. ^ Kahan, William. A Logarithm Too Clever by Half. [2008-11-14].
6. ^ ISO/IEC 9899:1999 specification (PDF). . p. 237, §7.12.11.3 The nextafter functions and §7.12.11.4 The nexttoward functions.
7. ^
8. ^