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