xref: /netbsd-src/lib/libm/src/s_nextafter.c (revision 53b02e147d4ed531c0d2a5ca9b3e8026ba3e99b5)
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 #if defined(LIBM_SCCS) && !defined(lint)
15 __RCSID("$NetBSD: s_nextafter.c,v 1.16 2017/08/16 11:22:52 he Exp $");
16 #endif
17 
18 /* IEEE functions
19  *	nextafter(x,y)
20  *	return the next machine floating-point number of x in the
21  *	direction toward y.
22  *   Special cases:
23  */
24 
25 #include "math.h"
26 #include "math_private.h"
27 
28 #ifndef __HAVE_LONG_DOUBLE
29 __strong_alias(nextafterl, nextafter)
30 __strong_alias(nexttoward, nextafter)
31 #endif
32 
33 double
34 nextafter(double x, double y)
35 {
36 	int32_t hx,hy,ix,iy;
37 	u_int32_t lx,ly;
38 
39 	EXTRACT_WORDS(hx,lx,x);
40 	EXTRACT_WORDS(hy,ly,y);
41 	ix = hx&0x7fffffff;		/* |x| */
42 	iy = hy&0x7fffffff;		/* |y| */
43 
44 	if(((ix>=0x7ff00000)&&((ix-0x7ff00000)|lx)!=0) ||   /* x is nan */
45 	   ((iy>=0x7ff00000)&&((iy-0x7ff00000)|ly)!=0))     /* y is nan */
46 	   return x+y;
47 	if(x==y) return y;		/* x=y, return y */
48 	if((ix|lx)==0) {			/* x == 0 */
49 	    INSERT_WORDS(x,hy&0x80000000,1);	/* return +-minsubnormal */
50 	    y = x*x;
51 	    if(y==x) return y; else return x;	/* raise underflow flag */
52 	}
53 	if(hx>=0) {				/* x > 0 */
54 	    if(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 	} else {				/* x < 0 */
62 	    if(hy>=0||hx>hy||((hx==hy)&&(lx>ly))){/* x < y, x -= ulp */
63 		if(lx==0) hx -= 1;
64 		lx -= 1;
65 	    } else {				/* x > y, x += ulp */
66 		lx += 1;
67 		if(lx==0) hx += 1;
68 	    }
69 	}
70 	hy = hx&0x7ff00000;
71 	if(hy>=0x7ff00000) return x+x;	/* overflow  */
72 	if(hy<0x00100000) {		/* underflow */
73 	    y = x*x;
74 	    if(y!=x) {		/* raise underflow flag */
75 	        INSERT_WORDS(y,hx,lx);
76 		return y;
77 	    }
78 	}
79 	INSERT_WORDS(x,hx,lx);
80 	return x;
81 }
82