This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: compile-time conversion of floating-point expressions to long longs
- From: "Nelson H. F. Beebe" <beebe at math dot utah dot edu>
- To: gcc-help at gcc dot gnu dot org
- Cc: beebe at math dot utah dot edu, Jim Cromie <jim dot cromie at gmail dot com>
- Date: Wed, 3 May 2006 16:57:05 -0600 (MDT)
- Subject: Re: compile-time conversion of floating-point expressions to long longs
Jim Cromie <jim.cromie@gmail.com> asks on Wed, 03 May 2006 12:17:38 -0400:
>> ...
>> Are there any macros that can tear into a floating point number and
>> pull out the exponent and mantissa ?
>> ...
Yes, the C89 and C99 ISO C Standards include ldexp(x,n), which forms x
* 2**n, and "f = frexp(x,&n);", which returns the fraction as a value
in [1/2,1) (or 0 if x is zero) and the exponent of 2 in n. Both are
exact, and can be implemented reasonably efficiently.
Two related, and useful, functions are
(1) modf(x,*y), which splits x into an integral part stored in y as an
exactly-representable floating-point number, and returns the
fractional part as the function value. Both have the same sign as x.
(2) fmod(x,y), which returns the remainder of x divided by y.
All four of these functions are EXACT; no rounding errors whatsoever
are possible. Note that for fmod(), the computation involves finding
the integer close to x/y, and that can be very large: in IEEE 754
128-bit arithmetic, it is a number of nearly 9900 decimal digits.
Fortunately, it is possible to implement fmod() iteratively, without
access to high-precision floating-point.
ldexp() and frexp() were in C in Unix Version 7 in the late 1970s; the
other two are more recent. You can safely use all four of them on
modern systems. Pre-C99 implementations may lack the float and long
double counterparts. However, glibc on GNU/Linux offers all twelve
variants.
-------------------------------------------------------------------------------
- Nelson H. F. Beebe Tel: +1 801 581 5254 -
- University of Utah FAX: +1 801 581 4148 -
- Department of Mathematics, 110 LCB Internet e-mail: beebe@math.utah.edu -
- 155 S 1400 E RM 233 beebe@acm.org beebe@computer.org -
- Salt Lake City, UT 84112-0090, USA URL: http://www.math.utah.edu/~beebe/ -
-------------------------------------------------------------------------------