/**************************************************************** The author of this software is David M. Gay. Copyright (C) 1998, 1999 by Lucent Technologies All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name of Lucent or any of its entities not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ****************************************************************/ /* * Freestanding i386-specific ulp implementation * derived from the FreeBSD gdtoa ulp.c file * by Diomidis Spinellis, August 2004 */ #include #include #include #define Exp_shift 20 #define Exp_msk1 0x100000 #define Exp_mask 0x7ff00000 #define P 53 #define word0(x) ((unsigned long *)&x)[1] #define word1(x) ((unsigned long *)&x)[0] double ulp(double x) { register long L; double a; L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1; if (L > 0) { word0(a) = L; word1(a) = 0; } else { L = -L >> Exp_shift; if (L < Exp_shift) { word0(a) = 0x80000 >> L; word1(a) = 0; } else { word0(a) = 0; L -= Exp_shift; word1(a) = L >= 31 ? 1 : 1 << (31 - L); } } return a; } #ifdef TEST /* Compile as cl -Op -DTEST ulp.c cc -ffloat-store -DTEST ulp.c You can also compile the FreeBSD 5.0 new grtdoa library ulp.c as cc -ffloat-store -DTEST -I/usr/src/lib/libc/include -I/usr/src/lib/libc/i386 ulp.c */ void ulptest(double x) { double u = ulp(x); double u2; again: u2 = u / 2.; if (x + u == x || x - u == x || x + u2 != x || x - u2 != x) printf("x=%.99g ulp=%.99g\nx+ulp=%.99g %s\nx-ulp=%.99g %s\nx+ulp/2=%.99g %s\nx-ulp/2=%.99g %s\n\n", x, u, x + u, (x == x + u) ? "EQ ***" : "NE", x - u, (x == x - u) ? "EQ ***" : "NE", x + u2, (x == x + u2) ? "EQ" : "NE ***", x - u2, (x == x - u2) ? "EQ" : "NE ***" ); if (x + u2 != x) { u = u - u2; printf("RETRY "); goto again; } if (x - u2 != x) { u = u2 - u; printf("RETRY "); goto again; } } main() { ulptest(1); ulptest(-1); ulptest(.5); ulptest(-.5); ulptest(30); ulptest(-30); ulptest(3e10); ulptest(-3e10); ulptest(DBL_MAX); ulptest(DBL_MIN); ulptest(DBL_EPSILON); } #endif // TEST