-3

I have a code that works using loop but it's bad imo, because can be simplified. I mean this loop:

    private static long GetFract(double d)
    {
        if (d < 0)
            return GetFract(-d);
        d -= Math.Truncate(d);
        long result = 0;
        checked
        {
            while (true)
            {
                try
                {
                    d *= 10;
                    long tmp = (long)d;
                    if (Math.Abs(tmp - d) < double.Epsilon)
                        return tmp;
                    result = tmp;
                }
                catch
                {
                    return result;
                }
            }
        }
    }

expected results: 2.3333 -> 3333

so can we use IEEE754 to get a fractional part of a number without using ToString(), Split() and other functions, using just FP and integer math? I mean some bit magic:

    private static unsafe long GetFract(double d)
    {
        if (d < 0)
            return GetFract(-d);
        d -= Math.Truncate(d);
        const long mask = 0xFFFFFFFFFFFFF; //some magic const here
        long x = *((long*) &d);
        return x & mask;
    }

we assume that d is always in [0..1], long and double are 8 bytes both

Alex Zhukovskiy
  • 9,565
  • 11
  • 75
  • 151
  • Sure, change the exponent after shifting out the left part... – deviantfan Jan 22 '15 at 22:01
  • 1
    You solved the title question in the first three lines, no loop. Your more complicated problem (which the comments don't really address) is finding a good approximation using a base-10 denominator. There's no direct way to do that, although you might use a binary loop instead of linear search. – Ben Voigt Jan 22 '15 at 22:22

1 Answers1

3

The sequence of bits representing the number 3333 is not found in the IEEE 754 representation of 2.3333, nor 0.3333, because IEEE 754 uses a binary exponent, not decimal.

That is, you are looking for the numerator in 3333 / 10000 but the internal representation is (when converted to decimal) 6004199023210345 / 18014398509481984 (that denominator is 254)

There's no bit hack that will extract data that isn't there in the first place.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720