Ejemplo n.º 1
0
        // Rounds the buffer upwards if the result is closer to v by possibly adding
        // 1 to the buffer. If the precision of the calculation is not sufficient to
        // round correctly, return false.
        // The rounding might shift the whole buffer in which case the kappa is
        // adjusted. For example "99", kappa = 3 might become "10", kappa = 4.
        //
        // If 2*rest > ten_kappa then the buffer needs to be round up.
        // rest can have an error of +/- 1 unit. This function accounts for the
        // imprecision and returns false, if the rounding direction cannot be
        // unambiguously determined.
        //
        // Precondition: rest < ten_kappa.
        static bool RoundWeedCounted(
            DtoaBuilder buffer,
            ulong rest,
            ulong ten_kappa,
            ulong unit,
            ref int kappa)
        {
            // The following tests are done in a specific order to avoid overflows. They
            // will work correctly with any uint64 values of rest < ten_kappa and unit.
            //
            // If the unit is too big, then we don't know which way to round. For example
            // a unit of 50 means that the real number lies within rest +/- 50. If
            // 10^kappa == 40 then there is no way to tell which way to round.
            if (unit >= ten_kappa)
            {
                return(false);
            }
            // Even if unit is just half the size of 10^kappa we are already completely
            // lost. (And after the previous test we know that the expression will not
            // over/underflow.)
            if (ten_kappa - unit <= unit)
            {
                return(false);
            }
            // If 2 * (rest + unit) <= 10^kappa we can safely round down.
            if ((ten_kappa - rest > rest) && (ten_kappa - 2 * rest >= 2 * unit))
            {
                return(true);
            }

            // If 2 * (rest - unit) >= 10^kappa, then we can safely round up.
            if ((rest > unit) && (ten_kappa - (rest - unit) <= (rest - unit)))
            {
                // Increment the last digit recursively until we find a non '9' digit.
                buffer._chars[buffer.Length - 1]++;
                for (int i = buffer.Length - 1; i > 0; --i)
                {
                    if (buffer._chars[i] != '0' + 10)
                    {
                        break;
                    }
                    buffer._chars[i] = '0';
                    buffer._chars[i - 1]++;
                }

                // If the first digit is now '0'+ 10 we had a buffer with all '9's. With the
                // exception of the first digit all digits are now '0'. Simply switch the
                // first digit to '1' and adjust the kappa. Example: "99" becomes "10" and
                // the power (the kappa) is increased.
                if (buffer._chars[0] == '0' + 10)
                {
                    buffer._chars[0] = '1';
                    kappa           += 1;
                }

                return(true);
            }

            return(false);
        }
Ejemplo n.º 2
0
        // Generates 'requested_digits' after the decimal point. It might omit
        // trailing '0's. If the input number is too small then no digits at all are
        // generated (ex.: 2 fixed digits for 0.00001).
        //
        // Input verifies:  1 <= (numerator + delta) / denominator < 10.
        static void BignumToFixed(
            int requested_digits,
            ref int decimal_point,
            Bignum numerator,
            Bignum denominator,
            DtoaBuilder buffer)
        {
            // Note that we have to look at more than just the requested_digits, since
            // a number could be rounded up. Example: v=0.5 with requested_digits=0.
            // Even though the power of v equals 0 we can't just stop here.
            if (-(decimal_point) > requested_digits)
            {
                // The number is definitively too small.
                // Ex: 0.001 with requested_digits == 1.
                // Set decimal-point to -requested_digits. This is what Gay does.
                // Note that it should not have any effect anyways since the string is
                // empty.
                decimal_point = -requested_digits;
                buffer.Reset();
                return;
            }

            if (-decimal_point == requested_digits)
            {
                // We only need to verify if the number rounds down or up.
                // Ex: 0.04 and 0.06 with requested_digits == 1.
                Debug.Assert(decimal_point == -requested_digits);
                // Initially the fraction lies in range (1, 10]. Multiply the denominator
                // by 10 so that we can compare more easily.
                denominator.Times10();
                if (Bignum.PlusCompare(numerator, numerator, denominator) >= 0)
                {
                    // If the fraction is >= 0.5 then we have to include the rounded
                    // digit.
                    buffer[0] = '1';
                    decimal_point++;
                }
                else
                {
                    // Note that we caught most of similar cases earlier.
                    buffer.Reset();
                }
            }
            else
            {
                // The requested digits correspond to the digits after the point.
                // The variable 'needed_digits' includes the digits before the point.
                int needed_digits = (decimal_point) + requested_digits;
                GenerateCountedDigits(needed_digits, ref decimal_point, numerator, denominator, buffer);
            }
        }
Ejemplo n.º 3
0
        // Let v = numerator / denominator < 10.
        // Then we generate 'count' digits of d = x.xxxxx... (without the decimal point)
        // from left to right. Once 'count' digits have been produced we decide wether
        // to round up or down. Remainders of exactly .5 round upwards. Numbers such
        // as 9.999999 propagate a carry all the way, and change the
        // exponent (decimal_point), when rounding upwards.
        static void GenerateCountedDigits(
            int count,
            ref int decimal_point,
            Bignum numerator,
            Bignum denominator,
            DtoaBuilder buffer)
        {
            Debug.Assert(count >= 0);
            for (int i = 0; i < count - 1; ++i)
            {
                uint d = numerator.DivideModuloIntBignum(denominator);
                Debug.Assert(d <= 9);  // digit is a uint and therefore always positive.
                // digit = numerator / denominator (integer division).
                // numerator = numerator % denominator.
                buffer.Append((char)(d + '0'));
                // Prepare for next iteration.
                numerator.Times10();
            }
            // Generate the last digit.
            uint digit = numerator.DivideModuloIntBignum(denominator);

            if (Bignum.PlusCompare(numerator, numerator, denominator) >= 0)
            {
                digit++;
            }
            buffer.Append((char)(digit + '0'));
            // Correct bad digits (in case we had a sequence of '9's). Propagate the
            // carry until we hat a non-'9' or til we reach the first digit.
            for (int i = count - 1; i > 0; --i)
            {
                if (buffer[i] != '0' + 10)
                {
                    break;
                }
                buffer[i] = '0';
                buffer[i - 1]++;
            }
            if (buffer[0] == '0' + 10)
            {
                // Propagate a carry past the top place.
                buffer[0] = '1';
                decimal_point++;
            }
        }
Ejemplo n.º 4
0
        // Adjusts the last digit of the generated number, and screens out generated
        // solutions that may be inaccurate. A solution may be inaccurate if it is
        // outside the safe interval, or if we ctannot prove that it is closer to the
        // input than a neighboring representation of the same length.
        //
        // Input: * buffer containing the digits of too_high / 10^kappa
        //        * distance_too_high_w == (too_high - w).f() * unit
        //        * unsafe_interval == (too_high - too_low).f() * unit
        //        * rest = (too_high - buffer * 10^kappa).f() * unit
        //        * ten_kappa = 10^kappa * unit
        //        * unit = the common multiplier
        // Output: returns true if the buffer is guaranteed to contain the closest
        //    representable number to the input.
        //  Modifies the generated digits in the buffer to approach (round towards) w.
        private static bool RoundWeed(
            DtoaBuilder buffer,
            ulong distanceTooHighW,
            ulong unsafeInterval,
            ulong rest,
            ulong tenKappa,
            ulong unit)
        {
            ulong smallDistance = distanceTooHighW - unit;
            ulong bigDistance   = distanceTooHighW + unit;

            // Let w_low  = too_high - big_distance, and
            //     w_high = too_high - small_distance.
            // Note: w_low < w < w_high
            //
            // The real w (* unit) must lie somewhere inside the interval
            // ]w_low; w_low[ (often written as "(w_low; w_low)")

            // Basically the buffer currently contains a number in the unsafe interval
            // ]too_low; too_high[ with too_low < w < too_high
            //
            //  too_high - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
            //                     ^v 1 unit            ^      ^                 ^      ^
            //  boundary_high ---------------------     .      .                 .      .
            //                     ^v 1 unit            .      .                 .      .
            //   - - - - - - - - - - - - - - - - - - -  +  - - + - - - - - -     .      .
            //                                          .      .         ^       .      .
            //                                          .  big_distance  .       .      .
            //                                          .      .         .       .    rest
            //                              small_distance     .         .       .      .
            //                                          v      .         .       .      .
            //  w_high - - - - - - - - - - - - - - - - - -     .         .       .      .
            //                     ^v 1 unit                   .         .       .      .
            //  w ----------------------------------------     .         .       .      .
            //                     ^v 1 unit                   v         .       .      .
            //  w_low  - - - - - - - - - - - - - - - - - - - - -         .       .      .
            //                                                           .       .      v
            //  buffer --------------------------------------------------+-------+--------
            //                                                           .       .
            //                                                  safe_interval    .
            //                                                           v       .
            //   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -     .
            //                     ^v 1 unit                                     .
            //  boundary_low -------------------------                     unsafe_interval
            //                     ^v 1 unit                                     v
            //  too_low  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
            //
            //
            // Note that the value of buffer could lie anywhere inside the range too_low
            // to too_high.
            //
            // boundary_low, boundary_high and w are approximations of the real boundaries
            // and v (the input number). They are guaranteed to be precise up to one unit.
            // In fact the error is guaranteed to be strictly less than one unit.
            //
            // Anything that lies outside the unsafe interval is guaranteed not to round
            // to v when read again.
            // Anything that lies inside the safe interval is guaranteed to round to v
            // when read again.
            // If the number inside the buffer lies inside the unsafe interval but not
            // inside the safe interval then we simply do not know and bail out (returning
            // false).
            //
            // Similarly we have to take into account the imprecision of 'w' when rounding
            // the buffer. If we have two potential representations we need to make sure
            // that the chosen one is closer to w_low and w_high since v can be anywhere
            // between them.
            //
            // By generating the digits of too_high we got the largest (closest to
            // too_high) buffer that is still in the unsafe interval. In the case where
            // w_high < buffer < too_high we try to decrement the buffer.
            // This way the buffer approaches (rounds towards) w.
            // There are 3 conditions that stop the decrementation process:
            //   1) the buffer is already below w_high
            //   2) decrementing the buffer would make it leave the unsafe interval
            //   3) decrementing the buffer would yield a number below w_high and farther
            //      away than the current number. In other words:
            //              (buffer{-1} < w_high) && w_high - buffer{-1} > buffer - w_high
            // Instead of using the buffer directly we use its distance to too_high.
            // Conceptually rest ~= too_high - buffer
            while (rest < smallDistance &&              // Negated condition 1
                   unsafeInterval - rest >= tenKappa && // Negated condition 2
                   (rest + tenKappa < smallDistance ||  // buffer{-1} > w_high
                    smallDistance - rest >= rest + tenKappa - smallDistance))
            {
                buffer.DecreaseLast();
                rest += tenKappa;
            }

            // We have approached w+ as much as possible. We now test if approaching w-
            // would require changing the buffer. If yes, then we have two possible
            // representations close to w, but we cannot decide which one is closer.
            if (rest < bigDistance &&
                unsafeInterval - rest >= tenKappa &&
                (rest + tenKappa < bigDistance ||
                 bigDistance - rest > rest + tenKappa - bigDistance))
            {
                return(false);
            }

            // Weeding test.
            //   The safe interval is [too_low + 2 ulp; too_high - 2 ulp]
            //   Since too_low = too_high - unsafe_interval this is equivalent to
            //      [too_high - unsafe_interval + 4 ulp; too_high - 2 ulp]
            //   Conceptually we have: rest ~= too_high - buffer
            return((2 * unit <= rest) && (rest <= unsafeInterval - 4 * unit));
        }
        public static void DoubleToAscii(
            DtoaBuilder buffer,
            double v,
            DtoaMode mode,
            int requested_digits,
            out bool negative,
            out int point)
        {
            Debug.Assert(!double.IsNaN(v));
            Debug.Assert(!double.IsInfinity(v));
            Debug.Assert(mode == DtoaMode.Shortest || requested_digits >= 0);

            point    = 0;
            negative = false;
            buffer.Reset();

            if (v < 0)
            {
                negative = true;
                v        = -v;
            }

            if (v == 0)
            {
                buffer[0] = '0';
                point     = 1;
                return;
            }

            if (mode == DtoaMode.Precision && requested_digits == 0)
            {
                return;
            }

            bool fast_worked = false;

            switch (mode)
            {
            case DtoaMode.Shortest:
                fast_worked = FastDtoa.NumberToString(v, DtoaMode.Shortest, 0, out point, buffer);
                break;

            case DtoaMode.Fixed:
                //fast_worked = FastFixedDtoa(v, requested_digits, buffer, length, point);
                ExceptionHelper.ThrowNotImplementedException();
                break;

            case DtoaMode.Precision:
                fast_worked = FastDtoa.NumberToString(v, DtoaMode.Precision, requested_digits, out point, buffer);
                break;

            default:
                ExceptionHelper.ThrowArgumentOutOfRangeException <string>();
                return;
            }

            if (fast_worked)
            {
                return;
            }

            // If the fast dtoa didn't succeed use the slower bignum version.
            buffer.Reset();
            BignumDtoa.NumberToString(v, mode, requested_digits, buffer, out point);
        }
Ejemplo n.º 6
0
        public static void NumberToString(
            double v,
            DtoaMode mode,
            int requested_digits,
            DtoaBuilder builder,
            out int decimal_point)
        {
            var bits                = (ulong)BitConverter.DoubleToInt64Bits(v);
            var significand         = DoubleHelper.Significand(bits);
            var is_even             = (significand & 1) == 0;
            var exponent            = DoubleHelper.Exponent(bits);
            var normalized_exponent = DoubleHelper.NormalizedExponent(significand, exponent);
            // estimated_power might be too low by 1.
            var estimated_power = EstimatePower(normalized_exponent);

            // Shortcut for Fixed.
            // The requested digits correspond to the digits after the point. If the
            // number is much too small, then there is no need in trying to get any
            // digits.
            if (mode == DtoaMode.Fixed && -estimated_power - 1 > requested_digits)
            {
                // Set decimal-point to -requested_digits. This is what Gay does.
                // Note that it should not have any effect anyways since the string is
                // empty.
                decimal_point = -requested_digits;
                return;
            }

            Bignum numerator   = new Bignum();
            Bignum denominator = new Bignum();
            Bignum delta_minus = new Bignum();
            Bignum delta_plus  = new Bignum();
            // Make sure the bignum can grow large enough. The smallest double equals
            // 4e-324. In this case the denominator needs fewer than 324*4 binary digits.
            // The maximum double is 1.7976931348623157e308 which needs fewer than
            // 308*4 binary digits.
            var need_boundary_deltas = mode == DtoaMode.Shortest;

            InitialScaledStartValues(
                v,
                estimated_power,
                need_boundary_deltas,
                numerator,
                denominator,
                delta_minus,
                delta_plus);
            // We now have v = (numerator / denominator) * 10^estimated_power.
            FixupMultiply10(
                estimated_power,
                is_even,
                out decimal_point,
                numerator,
                denominator,
                delta_minus,
                delta_plus);
            // We now have v = (numerator / denominator) * 10^(decimal_point-1), and
            //  1 <= (numerator + delta_plus) / denominator < 10
            switch (mode)
            {
            case DtoaMode.Shortest:
                GenerateShortestDigits(
                    numerator,
                    denominator,
                    delta_minus,
                    delta_plus,
                    is_even,
                    builder);
                break;

            case DtoaMode.Fixed:
                BignumToFixed(
                    requested_digits,
                    ref decimal_point,
                    numerator,
                    denominator,
                    builder);
                break;

            case DtoaMode.Precision:
                GenerateCountedDigits(
                    requested_digits,
                    ref decimal_point,
                    numerator,
                    denominator,
                    builder);
                break;

            default:
                ExceptionHelper.ThrowArgumentOutOfRangeException();
                break;
            }
        }
Ejemplo n.º 7
0
        // The procedure starts generating digits from the left to the right and stops
        // when the generated digits yield the shortest decimal representation of v. A
        // decimal representation of v is a number lying closer to v than to any other
        // double, so it converts to v when read.
        //
        // This is true if d, the decimal representation, is between m- and m+, the
        // upper and lower boundaries. d must be strictly between them if !is_even.
        //           m- := (numerator - delta_minus) / denominator
        //           m+ := (numerator + delta_plus) / denominator
        //
        // Precondition: 0 <= (numerator+delta_plus) / denominator < 10.
        //   If 1 <= (numerator+delta_plus) / denominator < 10 then no leading 0 digit
        //   will be produced. This should be the standard precondition.
        private static void GenerateShortestDigits(
            Bignum numerator,
            Bignum denominator,
            Bignum delta_minus,
            Bignum delta_plus,
            bool is_even,
            DtoaBuilder buffer)
        {
            // Small optimization: if delta_minus and delta_plus are the same just reuse
            // one of the two bignums.
            if (Bignum.Equal(delta_minus, delta_plus))
            {
                delta_plus = delta_minus;
            }

            buffer.Reset();
            while (true)
            {
                uint digit;
                digit = numerator.DivideModuloIntBignum(denominator);
                // digit = numerator / denominator (integer division).
                // numerator = numerator % denominator.
                buffer.Append((char)(digit + '0'));

                // Can we stop already?
                // If the remainder of the division is less than the distance to the lower
                // boundary we can stop. In this case we simply round down (discarding the
                // remainder).
                // Similarly we test if we can round up (using the upper boundary).
                bool in_delta_room_minus;
                bool in_delta_room_plus;
                if (is_even)
                {
                    in_delta_room_minus = Bignum.LessEqual(numerator, delta_minus);
                }
                else
                {
                    in_delta_room_minus = Bignum.Less(numerator, delta_minus);
                }
                if (is_even)
                {
                    in_delta_room_plus = Bignum.PlusCompare(numerator, delta_plus, denominator) >= 0;
                }
                else
                {
                    in_delta_room_plus = Bignum.PlusCompare(numerator, delta_plus, denominator) > 0;
                }
                if (!in_delta_room_minus && !in_delta_room_plus)
                {
                    // Prepare for next iteration.
                    numerator.Times10();
                    delta_minus.Times10();
                    // We optimized delta_plus to be equal to delta_minus (if they share the
                    // same value). So don't multiply delta_plus if they point to the same
                    // object.
                    if (delta_minus != delta_plus)
                    {
                        delta_plus.Times10();
                    }
                }
                else if (in_delta_room_minus && in_delta_room_plus)
                {
                    // Let's see if 2*numerator < denominator.
                    // If yes, then the next digit would be < 5 and we can round down.
                    int compare = Bignum.PlusCompare(numerator, numerator, denominator);
                    if (compare < 0)
                    {
                        // Remaining digits are less than .5. -> Round down (== do nothing).
                    }
                    else if (compare > 0)
                    {
                        // Remaining digits are more than .5 of denominator. . Round up.
                        // Note that the last digit could not be a '9' as otherwise the whole
                        // loop would have stopped earlier.
                        // We still have an assert here in case the preconditions were not
                        // satisfied.
                        buffer[buffer.Length - 1]++;
                    }
                    else
                    {
                        // Halfway case.
                        // TODO(floitsch): need a way to solve half-way cases.
                        //   For now let's round towards even (since this is what Gay seems to
                        //   do).

                        if ((buffer[buffer.Length - 1] - '0') % 2 == 0)
                        {
                            // Round down => Do nothing.
                        }
                        else
                        {
                            buffer[buffer.Length - 1]++;
                        }
                    }

                    return;
                }
                else if (in_delta_room_minus)
                {
                    // Round down (== do nothing).
                    return;
                }
                else
                {
                    // in_delta_room_plus
                    // Round up.
                    // Note again that the last digit could not be '9' since this would have
                    // stopped the loop earlier.
                    // We still have an DCHECK here, in case the preconditions were not
                    // satisfied.
                    buffer[buffer.Length - 1]++;
                    return;
                }
            }
        }