xref: /freebsd/lib/msun/src/s_nexttowardf.c (revision cf4c5a533126ca1ddb1f070af73f8f53b9e77fd4)
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 __FBSDID("$FreeBSD$");
14 
15 #include <float.h>
16 
17 #include "fpmath.h"
18 #include "math.h"
19 #include "math_private.h"
20 
21 #define	LDBL_INFNAN_EXP	(LDBL_MAX_EXP * 2 - 1)
22 
23 float
24 nexttowardf(float x, long double y)
25 {
26 	union IEEEl2bits uy;
27 	volatile float t;
28 	int32_t hx,ix;
29 
30 	GET_FLOAT_WORD(hx,x);
31 	ix = hx&0x7fffffff;		/* |x| */
32 	uy.e = y;
33 
34 	if((ix>0x7f800000) ||
35 	   (uy.bits.exp == LDBL_INFNAN_EXP &&
36 	    ((uy.bits.manh&~LDBL_NBIT)|uy.bits.manl) != 0))
37 	   return x+y;	/* x or y is nan */
38 	if(x==y) return (float)y;		/* x=y, return y */
39 	if(ix==0) {				/* x == 0 */
40 	    SET_FLOAT_WORD(x,(uy.bits.sign<<31)|1);/* return +-minsubnormal */
41 	    t = x*x;
42 	    if(t==x) return t; else return x;	/* raise underflow flag */
43 	}
44 	if(hx>=0 ^ x < y)			/* x -= ulp */
45 	    hx -= 1;
46 	else					/* x += ulp */
47 	    hx += 1;
48 	ix = hx&0x7f800000;
49 	if(ix>=0x7f800000) return x+x;	/* overflow  */
50 	if(ix<0x00800000) {		/* underflow */
51 	    t = x*x;
52 	    if(t!=x) {		/* raise underflow flag */
53 	        SET_FLOAT_WORD(y,hx);
54 		return y;
55 	    }
56 	}
57 	SET_FLOAT_WORD(x,hx);
58 	return x;
59 }
60