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