nexttoward.c 796 字节
Newer Older
R
Rich Felker 已提交
1
#include "libm.h"
2

R
Rich Felker 已提交
3 4 5 6 7
#if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024
double nexttoward(double x, long double y)
{
	return nextafter(x, y);
}
N
nsz 已提交
8 9 10
#else
#define SIGN ((uint64_t)1<<63)

R
Rich Felker 已提交
11 12
double nexttoward(double x, long double y)
{
N
nsz 已提交
13 14
	union dshape ux;
	int e;
R
Rich Felker 已提交
15

N
nsz 已提交
16 17
	if (isnan(x) || isnan(y))
		return x + y;
R
Rich Felker 已提交
18
	if (x == y)
N
nsz 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
		return y;
	ux.value = x;
	if (x == 0) {
		ux.bits = 1;
		if (signbit(y))
			ux.bits |= SIGN;
	} else if (x < y) {
		if (signbit(x))
			ux.bits--;
		else
			ux.bits++;
	} else {
		if (signbit(x))
			ux.bits++;
		else
			ux.bits--;
R
Rich Felker 已提交
35
	}
N
nsz 已提交
36 37 38
	e = ux.bits>>52 & 0x7ff;
	/* raise overflow if ux.value is infinite and x is finite */
	if (e == 0x7ff)
R
Rich Felker 已提交
39
		return x + x;
N
nsz 已提交
40
	/* raise underflow if ux.value is subnormal or zero */
41 42
	if (e == 0)
		FORCE_EVAL(x*x + ux.value*ux.value);
N
nsz 已提交
43
	return ux.value;
R
Rich Felker 已提交
44 45
}
#endif