Here's a challenge for floating point lovers.
Richard A. O'Keefe
ok at goanna.cs.rmit.oz.au
Fri Feb 1 18:01:07 AEST 1991
In article <1991Jan21.215629.8393 at watdragon.waterloo.edu>, rbutterworth at watdragon.waterloo.edu (Ray Butterworth) writes:
> Ever tried to come up with a manifest for a specific floating point value?
> Anyone know how to solve this problem in general,
There are several answers. One is that this is why "hex floats" are being
considered as an extension.
Here is a method for generating any floating-point value you want
*provided* that the machine's floating-point arithmetic uses a power of
2 as its radix, that converting small integers to floating point is
exact, that scaling is exact, and that addition is exact when it can be.
1. Figure out what bit pattern you want.
2. Divide it into convenient chunks, say 12-bit pieces.
For example, suppose that you want
[1].abc def x 2**k, where [1] is the hidden bit, abc is an 11 bit
number, and def is a 12-bit number. (This is going to be an IEEE single.)
We can represent the mantissa as a'bc x 2**(-12) + def x 2**(-24),
where a'bc is abc+512 (to restore the hidden bit). For example,
[1].5A3 2DF would be 0xDA3 x 2**(-12) + 0x2DF x 2**(-24)
3. Express the chunks using ldexp:
ldexp((double) 0x5A3, -12) + ldexp((double) 0x2DF, -24)
This should be exact. If it isn't, you have worse things to worry about.
4. Scale the result to provide the right exponent:
ldexp(ldexp(...,-12) + ldexp(...,-24) + ..., k)
If this doesn't work, you have worse problems to worry about than how to
get an exact constant.
There is one rather important thing to point out: PLEASE don't include
"magic numbers" in your program without providing a way to calculate them.
(The "way" might be a separate program.) If someone else tries to use your
code on a machine with a different floating-point system, and all they have
is your unexplained magic numbers, they will curse you and their answers
will be wrong. I have tried porting programs with 7 decimal digit constants
to a machine with nearly 12 decimal digits of precision, and it was no fun
at all.
--
The Marxists have merely _interpreted_ Marxism in various ways;
the point, however, is to _change_ it. -- R. Hochhuth.
More information about the Comp.lang.c
mailing list