s_ceill.c revision 140172
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 * From: @(#)s_ceil.c 5.1 93/09/24 12 */ 13 14#ifndef lint 15static char rcsid[] = "$FreeBSD: head/lib/msun/src/s_ceill.c 140172 2005-01-13 09:11:41Z stefanf $"; 16#endif 17 18/* 19 * ceill(x) 20 * Return x rounded toward -inf to integral value 21 * Method: 22 * Bit twiddling. 23 * Exception: 24 * Inexact flag raised if x not equal to ceill(x). 25 */ 26 27#include <float.h> 28#include <math.h> 29#include <stdint.h> 30 31#include "fpmath.h" 32 33#ifdef LDBL_IMPLICIT_NBIT 34#define MANH_SIZE (LDBL_MANH_SIZE + 1) 35#define INC_MANH(u, c) do { \ 36 uint64_t o = u.bits.manh; \ 37 u.bits.manh += (c); \ 38 if (u.bits.manh < o) \ 39 u.bits.exp++; \ 40} while (0) 41#else 42#define MANH_SIZE LDBL_MANH_SIZE 43#define INC_MANH(u, c) do { \ 44 uint64_t o = u.bits.manh; \ 45 u.bits.manh += (c); \ 46 if (u.bits.manh < o) { \ 47 u.bits.exp++; \ 48 u.bits.manh |= 1llu << (LDBL_MANH_SIZE - 1); \ 49 } \ 50} while (0) 51#endif 52 53long double 54ceill(long double x) 55{ 56 union IEEEl2bits u = { .e = x }; 57 int e = u.bits.exp - LDBL_MAX_EXP + 1; 58 59 if (e < MANH_SIZE - 1) { 60 if (e < 0) { /* raise inexact if x != 0 */ 61 if (u.bits.exp > 0 || (u.bits.manh | u.bits.manl) != 0) 62 u.e = u.bits.sign ? 0.0 : 1.0; 63 } else { 64 uint64_t m = ((1llu << MANH_SIZE) - 1) >> (e + 1); 65 if (((u.bits.manh & m) | u.bits.manl) == 0) 66 return (x); /* x is integral */ 67 /* raise inexact flag */ 68 if (!u.bits.sign) { 69#ifdef LDBL_IMPLICIT_NBIT 70 if (e == 0) 71 u.bits.exp++; 72 else 73#endif 74 INC_MANH(u, 1llu << (MANH_SIZE - e - 1)); 75 } 76 u.bits.manh &= ~m; 77 u.bits.manl = 0; 78 } 79 } else if (e < LDBL_MANT_DIG - 1) { 80 uint64_t m = (uint64_t)-1 >> (64 - LDBL_MANT_DIG + e + 1); 81 if ((u.bits.manl & m) == 0) 82 return (x); /* x is integral */ 83 /* raise inexact flag */ 84 if (!u.bits.sign) { 85 if (e == MANH_SIZE - 1) 86 INC_MANH(u, 1); 87 else { 88 uint64_t o = u.bits.manl; 89 u.bits.manl += 1llu << (LDBL_MANT_DIG - e - 1); 90 if (u.bits.manl < o) /* got a carry */ 91 INC_MANH(u, 1); 92 } 93 } 94 u.bits.manl &= ~m; 95 } 96 return (u.e); 97} 98