xref: /freebsd/lib/msun/src/s_nextafter.c (revision 2ad756a6bbb30fc98ee9000fba5bceec916a6c70)
1 /* @(#)s_nextafter.c 5.1 93/09/24 */
2 /*
3  * ====================================================
4  * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
5  *
6  * Developed at SunPro, a Sun Microsystems, Inc. business.
7  * Permission to use, copy, modify, and distribute this
8  * software is freely granted, provided that this notice
9  * is preserved.
10  * ====================================================
11  */
12 
13 #include <sys/cdefs.h>
14 /* IEEE functions
15  *	nextafter(x,y)
16  *	return the next machine floating-point number of x in the
17  *	direction toward y.
18  *   Special cases:
19  */
20 
21 #include <float.h>
22 
23 #include "math.h"
24 #include "math_private.h"
25 
26 double
27 nextafter(double x, double y)
28 {
29 	volatile double t;
30 	int32_t hx,hy,ix,iy;
31 	u_int32_t lx,ly;
32 
33 	EXTRACT_WORDS(hx,lx,x);
34 	EXTRACT_WORDS(hy,ly,y);
35 	ix = hx&0x7fffffff;		/* |x| */
36 	iy = hy&0x7fffffff;		/* |y| */
37 
38 	if(((ix>=0x7ff00000)&&((ix-0x7ff00000)|lx)!=0) ||   /* x is nan */
39 	   ((iy>=0x7ff00000)&&((iy-0x7ff00000)|ly)!=0))     /* y is nan */
40 	   return x+y;
41 	if(x==y) return y;		/* x=y, return y */
42 	if((ix|lx)==0) {			/* x == 0 */
43 	    INSERT_WORDS(x,hy&0x80000000,1);	/* return +-minsubnormal */
44 	    t = x*x;
45 	    if(t==x) return t; else return x;	/* raise underflow flag */
46 	}
47 	if(hx>=0) {				/* x > 0 */
48 	    if(hx>hy||((hx==hy)&&(lx>ly))) {	/* x > y, x -= ulp */
49 		if(lx==0) hx -= 1;
50 		lx -= 1;
51 	    } else {				/* x < y, x += ulp */
52 		lx += 1;
53 		if(lx==0) hx += 1;
54 	    }
55 	} else {				/* x < 0 */
56 	    if(hy>=0||hx>hy||((hx==hy)&&(lx>ly))){/* x < y, x -= ulp */
57 		if(lx==0) hx -= 1;
58 		lx -= 1;
59 	    } else {				/* x > y, x += ulp */
60 		lx += 1;
61 		if(lx==0) hx += 1;
62 	    }
63 	}
64 	hy = hx&0x7ff00000;
65 	if(hy>=0x7ff00000) return x+x;	/* overflow  */
66 	if(hy<0x00100000) {		/* underflow */
67 	    t = x*x;
68 	    if(t!=x) {		/* raise underflow flag */
69 	        INSERT_WORDS(y,hx,lx);
70 		return y;
71 	    }
72 	}
73 	INSERT_WORDS(x,hx,lx);
74 	return x;
75 }
76 
77 #if (LDBL_MANT_DIG == 53)
78 __weak_reference(nextafter, nexttoward);
79 __weak_reference(nextafter, nexttowardl);
80 __weak_reference(nextafter, nextafterl);
81 #endif
82