summaryrefslogtreecommitdiff
path: root/lib/libm/src/s_nextafterl.c
blob: 97efe4d584b2d655d48af49242289bd8098b1a36 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*	$NetBSD: s_nextafterl.c,v 1.5 2014/01/31 19:38:47 matt Exp $	*/

/* @(#)s_nextafter.c 5.1 93/09/24 */
/*
 * ====================================================
 * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
 *
 * Developed at SunPro, a Sun Microsystems, Inc. business.
 * Permission to use, copy, modify, and distribute this
 * software is freely granted, provided that this notice
 * is preserved.
 * ====================================================
 */

#include <sys/cdefs.h>
__RCSID("$NetBSD: s_nextafterl.c,v 1.5 2014/01/31 19:38:47 matt Exp $");

#include <float.h>
#include <math.h>
#include <machine/ieee.h>

#ifdef __HAVE_LONG_DOUBLE

#ifdef EXT_EXP_INFNAN
#if LDBL_MAX_EXP != 0x4000
#error "Unsupported long double format"
#endif

#ifdef LDBL_IMPLICIT_NBIT
#define	LDBL_NBIT	0
#endif

/*
 * IEEE functions
 *      nextafterl(x,y)
 *      return the next machine floating-point number of x in the
 *      direction toward y.
 *   Special cases:
 *	If x == y, y shall be returned
 *	If x or y is NaN, a NaN shall be returned
 */
long double
nextafterl(long double x, long double y)
{
	volatile long double t;
	union ieee_ext_u ux, uy;

	ux.extu_ld = x;
	uy.extu_ld = y;

	if ((ux.extu_exp == EXT_EXP_INFNAN &&
		((ux.extu_frach &~ LDBL_NBIT)|ux.extu_fracl) != 0) ||
	    (uy.extu_exp == EXT_EXP_INFNAN &&
		((uy.extu_frach &~ LDBL_NBIT)|uy.extu_fracl) != 0))
		return x+y;			/* x or y is nan */

	if (x == y) return y;			/* x=y, return y */

	if (x == 0.0) {
		ux.extu_frach = 0;		/* return +-minsubnormal */
		ux.extu_fracl = 1;
		ux.extu_sign = uy.extu_sign;
		t = ux.extu_ld * ux.extu_ld;
		if (t == ux.extu_ld)
			return t;
		else
			return ux.extu_ld;	/* raise underflow flag */
	}

	if ((x>0.0) ^ (x<y)) {			/* x -= ulp */
		if (ux.extu_fracl == 0) {
			if ((ux.extu_frach & ~LDBL_NBIT) == 0)
				ux.extu_exp -= 1;
			ux.extu_frach = (ux.extu_frach - 1) |
					(ux.extu_frach & LDBL_NBIT);
		}
		ux.extu_fracl -= 1;
	} else {				/* x += ulp */
		ux.extu_fracl += 1;
		if (ux.extu_fracl == 0) {
			ux.extu_frach = (ux.extu_frach + 1) |
					(ux.extu_frach & LDBL_NBIT);
			if ((ux.extu_frach & ~LDBL_NBIT) == 0)
				ux.extu_exp += 1;
		}
	}

	if (ux.extu_exp == EXT_EXP_INFNAN)
		return x+x;			/* overflow  */

	if (ux.extu_exp == 0) {			/* underflow */
#ifndef LDBL_IMPLICIT_NBIT
		mask_nbit_l(ux);
#endif
		t = ux.extu_ld * ux.extu_ld;
		if (t != ux.extu_ld)		/* raise underflow flag */
			return ux.extu_ld;
	}

	return ux.extu_ld;
}
#endif

#endif /* __HAVE_LONG_DOUBLE */