Home | History | Annotate | Line # | Download | only in src
      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.17 2024/05/05 22:10:06 riastradh 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 __strong_alias(nexttowardl, nextafter)
     32 #endif
     33 
     34 double
     35 nextafter(double x, double y)
     36 {
     37 	int32_t hx,hy,ix,iy;
     38 	u_int32_t lx,ly;
     39 
     40 	EXTRACT_WORDS(hx,lx,x);
     41 	EXTRACT_WORDS(hy,ly,y);
     42 	ix = hx&0x7fffffff;		/* |x| */
     43 	iy = hy&0x7fffffff;		/* |y| */
     44 
     45 	if(((ix>=0x7ff00000)&&((ix-0x7ff00000)|lx)!=0) ||   /* x is nan */
     46 	   ((iy>=0x7ff00000)&&((iy-0x7ff00000)|ly)!=0))     /* y is nan */
     47 	   return x+y;
     48 	if(x==y) return y;		/* x=y, return y */
     49 	if((ix|lx)==0) {			/* x == 0 */
     50 	    INSERT_WORDS(x,hy&0x80000000,1);	/* return +-minsubnormal */
     51 	    y = x*x;
     52 	    if(y==x) return y; else return x;	/* raise underflow flag */
     53 	}
     54 	if(hx>=0) {				/* x > 0 */
     55 	    if(hx>hy||((hx==hy)&&(lx>ly))) {	/* x > y, x -= ulp */
     56 		if(lx==0) hx -= 1;
     57 		lx -= 1;
     58 	    } else {				/* x < y, x += ulp */
     59 		lx += 1;
     60 		if(lx==0) hx += 1;
     61 	    }
     62 	} else {				/* x < 0 */
     63 	    if(hy>=0||hx>hy||((hx==hy)&&(lx>ly))){/* x < y, x -= ulp */
     64 		if(lx==0) hx -= 1;
     65 		lx -= 1;
     66 	    } else {				/* x > y, x += ulp */
     67 		lx += 1;
     68 		if(lx==0) hx += 1;
     69 	    }
     70 	}
     71 	hy = hx&0x7ff00000;
     72 	if(hy>=0x7ff00000) return x+x;	/* overflow  */
     73 	if(hy<0x00100000) {		/* underflow */
     74 	    y = x*x;
     75 	    if(y!=x) {		/* raise underflow flag */
     76 	        INSERT_WORDS(y,hx,lx);
     77 		return y;
     78 	    }
     79 	}
     80 	INSERT_WORDS(x,hx,lx);
     81 	return x;
     82 }
     83