xref: /freebsd/lib/msun/src/s_nexttoward.c (revision 06c3fb27)
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 #include <sys/cdefs.h>
13 /*
14  * We assume that a long double has a 15-bit exponent.  On systems
15  * where long double is the same as double, nexttoward() is an alias
16  * for nextafter(), so we don't use this routine.
17  */
18 
19 #include <float.h>
20 
21 #include "fpmath.h"
22 #include "math.h"
23 #include "math_private.h"
24 
25 #if LDBL_MAX_EXP != 0x4000
26 #error "Unsupported long double format"
27 #endif
28 
29 double
30 nexttoward(double x, long double y)
31 {
32 	union IEEEl2bits uy;
33 	volatile double t;
34 	int32_t hx,ix;
35 	u_int32_t lx;
36 
37 	EXTRACT_WORDS(hx,lx,x);
38 	ix = hx&0x7fffffff;		/* |x| */
39 	uy.e = y;
40 
41 	if(((ix>=0x7ff00000)&&((ix-0x7ff00000)|lx)!=0) ||
42 	    (uy.bits.exp == 0x7fff &&
43 	     ((uy.bits.manh&~LDBL_NBIT)|uy.bits.manl) != 0))
44 	   return x+y;	/* x or y is nan */
45 	if(x==y) return (double)y;		/* x=y, return y */
46 	if(x==0.0) {
47 	    INSERT_WORDS(x,uy.bits.sign<<31,1);	/* return +-minsubnormal */
48 	    t = x*x;
49 	    if(t==x) return t; else return x;	/* raise underflow flag */
50 	}
51 	if(hx>0.0 ^ x < y) {			/* x -= ulp */
52 	    if(lx==0) hx -= 1;
53 	    lx -= 1;
54 	} else {				/* x += ulp */
55 	    lx += 1;
56 	    if(lx==0) hx += 1;
57 	}
58 	ix = hx&0x7ff00000;
59 	if(ix>=0x7ff00000) return x+x;	/* overflow  */
60 	if(ix<0x00100000) {		/* underflow */
61 	    t = x*x;
62 	    if(t!=x) {		/* raise underflow flag */
63 	        INSERT_WORDS(x,hx,lx);
64 		return x;
65 	    }
66 	}
67 	INSERT_WORDS(x,hx,lx);
68 	return x;
69 }
70