Upload of drop-in replacement for Double:::toString(double)

raffaello.giulietti at gmail.com raffaello.giulietti at gmail.com
Fri Apr 20 13:32:30 UTC 2018


Hi Brian,

as agreed in [1], here is the first batch of my code. It includes
everything needed to replace Double::toString(double), if so wished. It
is accompanied by some JUnit tests in math.DoubleToDecimalTest and by
straightforward benchmarks in math.D2DBenchmark

The code still has notices attributing the copyright to me under the
GPL2 + Classpath exception license because I just copied the code
verbatim from my GitHub repo.

What is currently *not* included is the drop-in replacement for
Float.toString(float). Before I polish this part, which should take a
couple of hours, I'll wait for comments about the code delivered so far.

Source files are preceded by a line of the form:
-------- <filename>

They are
* LICENSE
* module-info.java
* math.Natural.java
* math.Powers.java
* math.MathUtils.java
* math.DoubleToDecimal.java
* math.DecimalChecker.java
* math.DoubleToDecimalTest.java
* math.D2DBenchmark.java

Let me know if the format I chose, namely dumb copy&paste, is appropriate.



Greetings
Raffaello

[1]
http://mail.openjdk.java.net/pipermail/core-libs-dev/2018-April/052681.html



-------- LICENSE

                    GNU GENERAL PUBLIC LICENSE
                       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

                    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

                            NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

    Gnomovision version 69, Copyright (C) year name of author
    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type
`show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  `Gnomovision' (which makes passes at compilers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

This General Public License does not permit incorporating your program into
proprietary programs.  If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.



"CLASSPATH" EXCEPTION TO THE GPL

Linking this library statically or dynamically with other modules is making
a combined work based on this library.  Thus, the terms and conditions of
the GNU General Public License cover the whole combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,
and to copy and distribute the resulting executable under terms of your
choice, provided that you also meet, for each linked independent module,
the terms and conditions of the license of that module.  An independent
module is a module which is not derived from or based on this library.  If
you modify this library, you may extend this exception to your version of
the library, but you are not obligated to do so.  If you do not wish to do
so, delete this exception statement from your version.

-------- module-info.java

/*
 * Copyright (c) 2018, Raffaello Giulietti. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 * This particular file is subject to the "Classpath" exception as provided
 * in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 */

module todec {
    exports math;
}

-------- math.Natural.java

/*
 * Copyright (c) 2018, Raffaello Giulietti. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 * This particular file is subject to the "Classpath" exception as provided
 * in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 */

package math;

import java.math.BigInteger;

import static java.lang.Math.max;

/**
 * A minimal, limited implementation of non-negative large integers.
 *
 * <p>All operations implemented here are needed in other parts of the
package,
 * while many are missing entirely because they are not needed.
 */
final class Natural {
    private static final long I_SZ = Integer.SIZE;
    private static final long I_MASK = (1L << I_SZ) - 1;
    private static final int I_MSB = -1 << I_SZ - 1;
    private static final long L_MSB = -1L << Long.SIZE - 1;

    /*
    A large natural is represented as a sequence of len B-ary digits,
    that is, in base
        B = 2^Integer.SIZE = 2^32
    Its value is
        d[0] + d[1]*B + d[2]*B^2 + ... + d[len-1]*B^(len-1)
    where each B-ary digit d[i] is interpreted as unsigned int.
    As usual, an empty sum has value 0, so if len = 0 then the value is 0.

    The following invariants hold:
        0 <= len <= d.length
        either len = 0 or d[len-1] != 0
     */
    private final int[] d;
    private final int len;

    private Natural(int[] d) {
        int i = d.length;
        while (--i >= 0 && d[i] == 0); // empty body intended
        this.len = i + 1;
        this.d = d;
    }

    /**
     * Returns a {@link Natural} with the same value as {@code v},
     * which is interpreted as an unsigned {@code long}.
     */
    static Natural valueOf(long v) {
        return new Natural(new int[]{(int) v, (int) (v >>> 32)});
    }

    /**
     * Returns a {@link Natural} with the value
     * {@code v} &#xb7; 2<sup>{@code n}</sup>.
     * The value {@code v} is interpreted as an unsigned {@code long} and
     * {@code n} must be non-negative.
     */
    static Natural valueOfShiftLeft(long v, int n) {
        // I_SZ = 2^5
        int q = n >> 5;
        int r = n & 0x1f;
        // length is q plus additional 2 for v and 1 for possible
overlapping
        int[] rd = new int[q + 3];
        rd[q] = (int) v << r;
        rd[q + 1] = (int) (v >>> I_SZ - r);
        // A safe shift by 64 - r, even when r = 0
        rd[q + 2] = (int) (v >>> I_SZ >>> I_SZ - r);
        return new Natural(rd);
    }

    /**
     * Returns -1, 0 or 1, depending on whether {@code this} is
     * &#x3c;, = or &#x3e; {@code y}, respectively.
     */
    int compareTo(Natural y) {
        if (len < y.len) {
            return -1;
        }
        if (len > y.len) {
            return 1;
        }
        int i = len;
        while (--i >= 0 && d[i] == y.d[i]); // empty body intended
        if (i < 0) {
            return 0;
        }
        // Perform an unsigned int comparision
        if ((d[i] ^ I_MSB) < (y.d[i] ^ I_MSB)) {
            return -1;
        }
        return 1;
    }

    /**
     * Returns -1, 0 or 1, depending on whether {@code this} is closer to
     * {@code x}, equally close to both {@code x} and {@code y} or closer to
     * {@code y}, respectively.
     */
    int closerTo(Natural x, Natural y) {
        /*
        computes (2 * this - x - y).compareTo(0) without allocating objects
        for the intermediate results.
         */
        int cmp = 0;
        long c = 0;
        int maxLen = max(max(x.len, y.len), len);
        for (int i = 0; i < maxLen; ++i) {
            long td = i < len ? d[i] & I_MASK : 0;
            long xd = i < x.len ? x.d[i] & I_MASK : 0;
            long yd = i < y.len ? y.d[i] & I_MASK : 0;
            long s = (td << 1) - xd - yd + c;
            cmp |= (int) s;
            c = s >> I_SZ;
        }
        if (c < 0) {
            return -1;
        }
        if (cmp != 0) {
            return 1;
        }
        return 0;
    }

    /**
     * Returns {@code this} * {@code y}, where {@code y} is taken as an
     * unsigned {@code long}.
     */
    Natural multiply(long y) {
        // Straightforward paper-and-pencil method for multiplication.
        int[] rd = new int[len + 2];
        long y0 = y & I_MASK;
        long y1 = y >>> I_SZ;
        long c = 0;
        long r1 = 0;
        long q0 = 0;
        long q1 = 0;
        long s;
        int i = 0;
        for (; i < len; ++i) {
            long td = d[i] & I_MASK;
            long p0 = y0 * td;
            s = (r1 >>> I_SZ) + (q0 >>> I_SZ) +
                    (q1 & I_MASK) + (p0 & I_MASK) + c;
            rd[i] = (int) s;
            c = s >>> I_SZ;
            r1 = q1;
            q0 = p0;
            q1 = y1 * td;
        }
        s = (r1 >>> I_SZ) + (q0 >>> I_SZ) + (q1 & I_MASK) + c;
        rd[i] = (int) s;
        c = s >>> I_SZ;
        rd[i + 1] = (int) (c + (q1 >>> I_SZ));
        return new Natural(rd);
    }

    /**
     * Returns {@code this} - {@code y}, where it is assumed that
     * {@code this} &#x2265; {@code y}.
     */
    Natural subtract(Natural y) {
        int[] rd = new int[len];
        long c = 0;
        int i = 0;
        for (; i < y.len; ++i) {
            long s = (d[i] & I_MASK) - (y.d[i] & I_MASK) + c;
            rd[i] = (int) s;
            c = s >> I_SZ;
        }
        for (; i < len; ++i) {
            long s = (d[i] & I_MASK) + c;
            rd[i] = (int) s;
            c = s >> I_SZ;
        }
        return new Natural(rd);
    }

    /**
     * Returns &#x23a3;{@code this} &#xb7; 2<sup>-{@code n}</sup>&#x23a6;,
     * where it is assumed that {@code n} &#x2265; 0 and that the result
     * is an unsigned {@code long}.
     */
    long shiftRight(int n) {
        int q = n >> 5;
        int r = n & 0x1f;
        long d0 = d[q] & I_MASK;
        long d1 = d[q + 1] & I_MASK;
        long d2 = q + 2 < len ? d[q + 2] & I_MASK : 0;
        // The double shift is safe even when r = 0
        return d0 >>> r | d1 << I_SZ - r | d2 << I_SZ << I_SZ - r;
    }

    /**
     * Returns {@code this} + {@code y} &#xb7; 2<sup>{@code n}</sup>,
     * where it is assumed that {@code n} &#x2265; 0.
     */
    Natural addShiftLeft(Natural y, int n) {
        int maxLen = max(len, y.len);
        int[] rd = new int[maxLen + 1];

        long c = 0;
        long yd = 0;
        int i = 0;
        for (; i < maxLen; ++i) {
            long t0 = i < len ? d[i] & I_MASK : 0;
            long y0 = i < y.len ? y.d[i] & I_MASK : 0;
            yd = yd >>> I_SZ | y0 << n;
            long s = t0 + (yd & I_MASK) + c;
            rd[i] = (int) s;
            c = s >>> I_SZ;
        }
        rd[i] = (int) ((yd >>> I_SZ) + c);
        return new Natural(rd);
    }

    private BigInteger toBigInteger() {
        // additional 1 for the "sign" most significant byte at index 0
        byte[] b = new byte[1 + (len << 2)];
        for (int i = 1; i <= len; ++i) {
            int d0 = d[len - i];
            b[(i << 2) - 3] = (byte) (d0 >>> 24);
            b[(i << 2) - 2] = (byte) (d0 >>> 16);
            b[(i << 2) - 1] = (byte) (d0 >>> 8);
            b[i << 2] = (byte) d0;
        }
        return new BigInteger(b);
    }

    /*
    Here for debugging purposes only. There's otherwise no need for it.
     */
    @Override
    public String toString() {
        // Quick-and-dirty solution to avoid implementing a special
division.
        return toBigInteger().toString();
    }

    /*
    Assumes 0 <= n
     */
    private Natural shiftLeft(int n) {
        int q = n >> 5;
        int r = n & 0x1f;
        // Allocates one int more than necessary to simplify the division
        if (r == 0) {
            int[] rd = new int[len + q + 1];
            for (int i = 0; i < len; ++i) {
                rd[q + i] = d[i];
            }
            return new Natural(rd);
        }
        int[] rd = new int[len + q + 2];
        rd[q] = d[0] << r;
        int i = 1;
        for (; i < len; ++i) {
            // safe shift, as 0 < r < I_SZ
            rd[q + i] = d[i] << r | d[i - 1] >>> I_SZ - r;
        }
        rd[q + i] = d[i - 1] >>> I_SZ - r;
        return new Natural(rd);
    }

    /**
     * Returns &#x23a3;{@code this} / {@code y}&#x23a6;.
     * <p>Assumes that:
     * <ul>
     * <li> {@code this} &#x2265; 2<sup>32</sup>.
     * <li> {@code y} &#x3e; 0.
     * <li> The result is an unsigned {@code long} &#x2265; 2<sup>32</sup>.
     * </ul>
     */
    long divide(Natural y) {
        int r = Integer.numberOfLeadingZeros(y.d[y.len - 1]) - 1 & 0x1f;
        // Ensure that v.len >= 2 and that vp meets the inequalities below
        if (y.len == 1) {
            r += I_SZ;
        }
        Natural u = shiftLeft(r);
        Natural v = y.shiftLeft(r);
        // by construction, 2^30 <= vp < 2^31: no need for masking
        long vp = v.d[v.len - 1];
        long v_n2 = v.d[v.len - 2] & I_MASK;
        long q = 0;
        for (int k = 1; k >= 0; --k) {
            int n = v.len + k;
            // this assumes that n <= u.d.length
            long up = (long) u.d[n] << I_SZ | u.d[n - 1] & I_MASK;
            long qb = up / vp;
            if (qb > I_MASK) qb = I_MASK;
            long rb = up - qb * vp;
            while (rb <= I_MASK &&
                    (qb * v_n2 ^ L_MSB) >
                            ((rb << I_SZ | u.d[n - 2] & I_MASK) ^ L_MSB)) {
                qb -= 1;
                rb += vp;
            }
            long s = 0;
            int i = 0;
            for (; i < v.len; ++i) {
                long p = qb * (v.d[i] & I_MASK) + s;
                long t = (u.d[i + k] & I_MASK) - (p & I_MASK);
                u.d[i + k] = (int) t;
                s = (p >>> I_SZ) - (t >> I_SZ);
            }
            long t = (u.d[i + k] & I_MASK) - (s & I_MASK);
            u.d[i + k] = (int) t;
            s = -(t >> I_SZ);
            if (s > 0) {
                qb -= 1;
                s = 0;
                for (i = 0; i < v.len; ++i) {
                    t = (u.d[i + k] & I_MASK) + (v.d[i] & I_MASK) + s;
                    u.d[i + k] = (int) t;
                    s = t >>> I_SZ;
                }
            }
            q = q << I_SZ | qb;
        }
        return q;
    }

}

-------- math.Powers.java

/*
 * Copyright (c) 2018, Raffaello Giulietti. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 * This particular file is subject to the "Classpath" exception as provided
 * in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 */

package math;

import static math.Natural.valueOf;

/**
 * Package-privately exposes
 * <ul>
 * <li> integer powers of 5 as unsigned {@code long}s, up to the exponent
 * {@link #MAX_POW_5_EXP}
 * <li> integer powers of 10 as unsigned {@code long}s, up to the exponent
 * {@link #MAX_POW_10_EXP}
 * <li> integer powers of 5 as {@link Natural}s, up to the exponent
 * {@link #MAX_POW_5_N_EXP}
 * </ul>
 *
 * <p>
 * Since this is a package-private class, no checks are made to ensure
 * that usages are correct.
 */
final class Powers {

    /**
     * The integer <i>e</i> such that
     * 5<sup><i>e</i></sup> &#x2264; <i>M</i> &#x3c; 5<sup><i>e</i>+1</sup>,
     * where <i>M</i> is the largest unsigned {@code long}, namely
     * <i>M</i> = 2<sup>{@link Long#SIZE}</sup> - 1.
     */
    static final int MAX_POW_5_EXP = 27;

    /*
    The greatest power of 5 fitting in an unsigned {@code long},
    namely 5^MAX_POW_5_EXP
     */
    private static final long MAX_POW_5 = 7_450_580_596_923_828_125L;

    /**
     * The integer <i>e</i> such that
     * 10<sup><i>e</i></sup> &#x2264; <i>M</i> &#x3c;
10<sup><i>e</i>+1</sup>,
     * where <i>M</i> is the largest unsigned {@code long}, namely
     * <i>M</i> = 2<sup>{@link Long#SIZE}</sup> - 1.
     */
    static final int MAX_POW_10_EXP = 19;

    /**
     * The greatest exponent for {@link #pow5(int)}.
     */
    /*
    MAX_POW_5_N_EXP = Double.H - Double.E_MIN_VALUE
     */
    static final int MAX_POW_5_N_EXP = 340;

    /**
     * Powers of 5, as unsigned {@code long}s, for exponents between
     * 0 and {@link #MAX_POW_5_EXP}.
     */
    static final long[] pow5;

    /**
     * Powers of 10, as unsigned {@code long}s, for exponents between
     * 0 and {@link #MAX_POW_10_EXP}.
     */
    static final long[] pow10;

    /*
    pow5n is populated lazily. More precisely, values for the exponents
between
    0 and MAX_POW_5_EXP are initialized upon class loading.
    Other values are computed upon request (see pow5()).

    Invariant:
        e0max is a multiple of MAX_POW_5_EXP and all values for exponents
        that are multiples of MAX_POW_5_EXP, up to e0max, are already
present
        in the array.
     */
    private static final Natural[] pow5n;
    private static int e0max = MAX_POW_5_EXP;

    static {
        /*
        Fully initializes the pow5 and pow10 array and partial initializes
        pow5n, which will be populated lazily, as need arises.
         */
        pow5n = new Natural[MAX_POW_5_N_EXP + 1];
        pow5 = new long[MAX_POW_5_EXP + 1];
        pow5[0] = 1;
        for (int k = 1; k < pow5.length; ++k) {
            pow5[k] = 5 * pow5[k - 1];
            pow5n[k] = valueOf(pow5[k]);
        }

        pow10 = new long[MAX_POW_10_EXP + 1];
        pow10[0] = 1;
        for (int k = 1; k < pow10.length; ++k) {
            pow10[k] = 10 * pow10[k - 1];
        }
    }

    private Powers() {
    }

    /**
     * Powers of 5, for exponents between 0 and {@link #MAX_POW_5_N_EXP}.
     */
    static synchronized Natural pow5(int e) {
        if (pow5n[e] != null) {
            return pow5n[e];
        }
        int e0 = e / MAX_POW_5_EXP * MAX_POW_5_EXP;
        /*
        Guard for the loop: mathematically not necessary but measurably
        enhances performance when there's no need to enter the loop.
         */
        if (e0max < e0) {
            for (; e0max < e0; e0max += MAX_POW_5_EXP) {
                pow5n[e0max + MAX_POW_5_EXP] =
pow5n[e0max].multiply(MAX_POW_5);
            }
        }
        if (e0 < e) {
            pow5n[e] = pow5n[e0].multiply(pow5[e - e0]);
        }
        return pow5n[e];
    }

}

-------- math.MathUtils.java

/*
 * Copyright (c) 2018, Raffaello Giulietti. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 * This particular file is subject to the "Classpath" exception as provided
 * in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 */

package math;

import static math.DoubleToDecimal.Double.c;
import static math.DoubleToDecimal.Double.q;

final class MathUtils {

    private static final int I = Integer.SIZE;
    private static final long MASK_I = (1L << I) - 1;

    /*
    The doubles below are expressed in hex notation to avoid possible
anomalies
    during decimal tokenization. Hex tokenization is assumed to be
completely
    reliable, as it is simpler from a mathematical perspective.
     */

    // The double closest to log10(2), 0.3010299956639812 in decimal
    private static final double LOG_10_2 = 0x1.34413509F79FFp-2;

    // The double closest to log2(10), 3.321928094887362 in decimal
    private static final double LOG_2_10 = 0x1.A934F0979A371p1;

    /**
     * The minimum exponent for {@link #floorPow10d(int)}
     * and {@link #pow10r(int)}
     */
    static final int MIN_EXP = -324;

    /**
     * The maximum exponent for {@link #floorPow10d(int)}
     * and {@link #pow10r(int)}
     */
    static final int MAX_EXP = 324;

    private MathUtils() {
    }

    /*
    This implementation is simple but is restricted to its usage here, when
    the assumptions below hold.

    It assumes
        v = 0 (thus c = 0) or 0 <= -q < Long.SIZE

    Also note that for v < 0
        floor(v) = -ceil(-v)
     */
    private static int floor(double v) {
        if (v >= 0) {
            long bits = java.lang.Double.doubleToRawLongBits(v);
            return (int) (c(bits) >>> -q(bits));
        }
        long bits = java.lang.Double.doubleToRawLongBits(-v);
        int q = q(bits);
        return -(int) (c(bits) + (1L << -q) - 1 >>> -q);
    }

    /**
     * Returns the integer <i>k</i> such that 10<sup><i>k</i>-1</sup>
&#x2264;
     * 2<sup>{@code e}</sup> &#x3c; 10<sup><i>k</i></sup>.
     * <p>
     * The result is correct when -198'096'464 &#x2264; {@code e} &#x2264;
     * 146'964'307.
     * Otherwise the result may or may not be correct.
     */
    static int ord10pow2(int e) {
        return floor(e * LOG_10_2) + 1;
    }

    /**
     * Returns the integer <i>k</i> such that 2<sup><i>k</i>-1</sup>
&#x2264;
     * 10<sup>{@code e}</sup> &#x3c; 2<sup><i>k</i></sup>.
     * <p>
     * The result is correct when -44'240'664 &#x2264; {@code e} &#x2264;
     * 59'632'977.
     * Otherwise the result may or may not be correct.
     */
    static int ord2pow10(int e) {
        return floor(e * LOG_2_10) + 1;
    }

    /**
     * Returns the high {@link Long#SIZE} bits of the full product
     * {@code x}{@code y}, namely
     * &#x23a3;{@code x}{@code y} &#xb7; 2<sup>-{@link
Long#SIZE}</sup>&#x23a6;.
     * <p>
     * Both {@code x} and {@code y} as well as the result are interpreted as
     * unsigned {@code long}s.
     */
    static long multiplyHighUnsigned(long x, long y) {
        /*
        Unfortunately, the plain version of Karatsuba cannot be applied
here:
        the mixed product would overflow with unrecoverable loss of bits.
        Thus, the plain paper-and-pencil scheme requiring 4 long
        multiplications is used.

        This could be a good candidate a for JIT compiler intrinsic.
         */
        final long x1 = x >>> I;
        final long x0 = x & MASK_I;
        final long y1 = y >>> I;
        final long y0 = y & MASK_I;
        final long x1y0 = x1 * y0;
        final long x0y1 = x0 * y1;
        return x1 * y1 +
                (x0y1 >>> I) +
                (x1y0 >>> I) +
                ((x0y1 & MASK_I) + (x1y0 & MASK_I) + (x0 * y0 >>> I) >>> I);
    }

    /**
     * Returns one of two components of an approximation of a power of 10.
     *
     * <p>More precisely, let
     * 10<sup>{@code e}</sup> = <i>d</i> &#xb7; 2<sup><i>r</i></sup>
     * for some integer <i>r</i> and real <i>d</i> with
     * 2<sup>{@link Long#SIZE}-1</sup> &#x2264; <i>d</i> &#x3c;
     * 2<sup>{@link Long#SIZE}</sup>.
     *
     * <p>This method returns &#x23a3;<i>d</i>&#x23a6; as an
     * unsigned {@code long}, while {@link #pow10r(int)} returns <i>r</i>.
     *
     * @param e  The exponent of the power of 10, bounded by
     *           {@link #MIN_EXP} &#x2264; {@code e} &#x2264; {@link
#MAX_EXP}
     * @see #pow10r(int)
     */
    static long floorPow10d(int e) {
        return floorPow10d[e - MIN_EXP];
    }

    /**
     * Returns one of two components of an approximation of a power of 10.
     *
     * <p>This method returns <i>r</i> from the representation described in
     * {@link #floorPow10d(int)}.
     *
     * @param e  The exponent of the power of 10, bounded by
     *           {@link #MIN_EXP} &#x2264; {@code e} &#x2264; {@link
#MAX_EXP}
     * @see #floorPow10d(int)
     */
    static int pow10r(int e) {
        return ord2pow10(e) - Long.SIZE;
    }

    /*
    The array has been computed and checked using full precision.
    The values are prefixed with a comment indicating the exponent.

    Contrary to common coding conventions, its definition is located here,
    at the end of the file, because the length of its source would be
    distracting for reading the rest.
     */
    private static final long[] floorPow10d = {
        /* -324 */ 0xCF42_894A_5DCE_35EAL,
        /* -323 */ 0x8189_95CE_7AA0_E1B2L,
        /* -322 */ 0xA1EB_FB42_1949_1A1FL,
        /* -321 */ 0xCA66_FA12_9F9B_60A6L,
        /* -320 */ 0xFD00_B897_4782_38D0L,
        /* -319 */ 0x9E20_735E_8CB1_6382L,
        /* -318 */ 0xC5A8_9036_2FDD_BC62L,
        /* -317 */ 0xF712_B443_BBD5_2B7BL,
        /* -316 */ 0x9A6B_B0AA_5565_3B2DL,
        /* -315 */ 0xC106_9CD4_EABE_89F8L,
        /* -314 */ 0xF148_440A_256E_2C76L,
        /* -313 */ 0x96CD_2A86_5764_DBCAL,
        /* -312 */ 0xBC80_7527_ED3E_12BCL,
        /* -311 */ 0xEBA0_9271_E88D_976BL,
        /* -310 */ 0x9344_5B87_3158_7EA3L,
        /* -309 */ 0xB815_7268_FDAE_9E4CL,
        /* -308 */ 0xE61A_CF03_3D1A_45DFL,
        /* -307 */ 0x8FD0_C162_0630_6BABL,
        /* -306 */ 0xB3C4_F1BA_87BC_8696L,
        /* -305 */ 0xE0B6_2E29_29AB_A83CL,
        /* -304 */ 0x8C71_DCD9_BA0B_4925L,
        /* -303 */ 0xAF8E_5410_288E_1B6FL,
        /* -302 */ 0xDB71_E914_32B1_A24AL,
        /* -301 */ 0x8927_31AC_9FAF_056EL,
        /* -300 */ 0xAB70_FE17_C79A_C6CAL,
        /* -299 */ 0xD64D_3D9D_B981_787DL,
        /* -298 */ 0x85F0_4682_93F0_EB4EL,
        /* -297 */ 0xA76C_5823_38ED_2621L,
        /* -296 */ 0xD147_6E2C_0728_6FAAL,
        /* -295 */ 0x82CC_A4DB_8479_45CAL,
        /* -294 */ 0xA37F_CE12_6597_973CL,
        /* -293 */ 0xCC5F_C196_FEFD_7D0CL,
        /* -292 */ 0xFF77_B1FC_BEBC_DC4FL,
        /* -291 */ 0x9FAA_CF3D_F736_09B1L,
        /* -290 */ 0xC795_830D_7503_8C1DL,
        /* -289 */ 0xF97A_E3D0_D244_6F25L,
        /* -288 */ 0x9BEC_CE62_836A_C577L,
        /* -287 */ 0xC2E8_01FB_2445_76D5L,
        /* -286 */ 0xF3A2_0279_ED56_D48AL,
        /* -285 */ 0x9845_418C_3456_44D6L,
        /* -284 */ 0xBE56_91EF_416B_D60CL,
        /* -283 */ 0xEDEC_366B_11C6_CB8FL,
        /* -282 */ 0x94B3_A202_EB1C_3F39L,
        /* -281 */ 0xB9E0_8A83_A5E3_4F07L,
        /* -280 */ 0xE858_AD24_8F5C_22C9L,
        /* -279 */ 0x9137_6C36_D999_95BEL,
        /* -278 */ 0xB585_4744_8FFF_FB2DL,
        /* -277 */ 0xE2E6_9915_B3FF_F9F9L,
        /* -276 */ 0x8DD0_1FAD_907F_FC3BL,
        /* -275 */ 0xB144_2798_F49F_FB4AL,
        /* -274 */ 0xDD95_317F_31C7_FA1DL,
        /* -273 */ 0x8A7D_3EEF_7F1C_FC52L,
        /* -272 */ 0xAD1C_8EAB_5EE4_3B66L,
        /* -271 */ 0xD863_B256_369D_4A40L,
        /* -270 */ 0x873E_4F75_E222_4E68L,
        /* -269 */ 0xA90D_E353_5AAA_E202L,
        /* -268 */ 0xD351_5C28_3155_9A83L,
        /* -267 */ 0x8412_D999_1ED5_8091L,
        /* -266 */ 0xA517_8FFF_668A_E0B6L,
        /* -265 */ 0xCE5D_73FF_402D_98E3L,
        /* -264 */ 0x80FA_687F_881C_7F8EL,
        /* -263 */ 0xA139_029F_6A23_9F72L,
        /* -262 */ 0xC987_4347_44AC_874EL,
        /* -261 */ 0xFBE9_1419_15D7_A922L,
        /* -260 */ 0x9D71_AC8F_ADA6_C9B5L,
        /* -259 */ 0xC4CE_17B3_9910_7C22L,
        /* -258 */ 0xF601_9DA0_7F54_9B2BL,
        /* -257 */ 0x99C1_0284_4F94_E0FBL,
        /* -256 */ 0xC031_4325_637A_1939L,
        /* -255 */ 0xF03D_93EE_BC58_9F88L,
        /* -254 */ 0x9626_7C75_35B7_63B5L,
        /* -253 */ 0xBBB0_1B92_8325_3CA2L,
        /* -252 */ 0xEA9C_2277_23EE_8BCBL,
        /* -251 */ 0x92A1_958A_7675_175FL,
        /* -250 */ 0xB749_FAED_1412_5D36L,
        /* -249 */ 0xE51C_79A8_5916_F484L,
        /* -248 */ 0x8F31_CC09_37AE_58D2L,
        /* -247 */ 0xB2FE_3F0B_8599_EF07L,
        /* -246 */ 0xDFBD_CECE_6700_6AC9L,
        /* -245 */ 0x8BD6_A141_0060_42BDL,
        /* -244 */ 0xAECC_4991_4078_536DL,
        /* -243 */ 0xDA7F_5BF5_9096_6848L,
        /* -242 */ 0x888F_9979_7A5E_012DL,
        /* -241 */ 0xAAB3_7FD7_D8F5_8178L,
        /* -240 */ 0xD560_5FCD_CF32_E1D6L,
        /* -239 */ 0x855C_3BE0_A17F_CD26L,
        /* -238 */ 0xA6B3_4AD8_C9DF_C06FL,
        /* -237 */ 0xD060_1D8E_FC57_B08BL,
        /* -236 */ 0x823C_1279_5DB6_CE57L,
        /* -235 */ 0xA2CB_1717_B524_81EDL,
        /* -234 */ 0xCB7D_DCDD_A26D_A268L,
        /* -233 */ 0xFE5D_5415_0B09_0B02L,
        /* -232 */ 0x9EFA_548D_26E5_A6E1L,
        /* -231 */ 0xC6B8_E9B0_709F_109AL,
        /* -230 */ 0xF867_241C_8CC6_D4C0L,
        /* -229 */ 0x9B40_7691_D7FC_44F8L,
        /* -228 */ 0xC210_9436_4DFB_5636L,
        /* -227 */ 0xF294_B943_E17A_2BC4L,
        /* -226 */ 0x979C_F3CA_6CEC_5B5AL,
        /* -225 */ 0xBD84_30BD_0827_7231L,
        /* -224 */ 0xECE5_3CEC_4A31_4EBDL,
        /* -223 */ 0x940F_4613_AE5E_D136L,
        /* -222 */ 0xB913_1798_99F6_8584L,
        /* -221 */ 0xE757_DD7E_C074_26E5L,
        /* -220 */ 0x9096_EA6F_3848_984FL,
        /* -219 */ 0xB4BC_A50B_065A_BE63L,
        /* -218 */ 0xE1EB_CE4D_C7F1_6DFBL,
        /* -217 */ 0x8D33_60F0_9CF6_E4BDL,
        /* -216 */ 0xB080_392C_C434_9DECL,
        /* -215 */ 0xDCA0_4777_F541_C567L,
        /* -214 */ 0x89E4_2CAA_F949_1B60L,
        /* -213 */ 0xAC5D_37D5_B79B_6239L,
        /* -212 */ 0xD774_85CB_2582_3AC7L,
        /* -211 */ 0x86A8_D39E_F771_64BCL,
        /* -210 */ 0xA853_0886_B54D_BDEBL,
        /* -209 */ 0xD267_CAA8_62A1_2D66L,
        /* -208 */ 0x8380_DEA9_3DA4_BC60L,
        /* -207 */ 0xA461_1653_8D0D_EB78L,
        /* -206 */ 0xCD79_5BE8_7051_6656L,
        /* -205 */ 0x806B_D971_4632_DFF6L,
        /* -204 */ 0xA086_CFCD_97BF_97F3L,
        /* -203 */ 0xC8A8_83C0_FDAF_7DF0L,
        /* -202 */ 0xFAD2_A4B1_3D1B_5D6CL,
        /* -201 */ 0x9CC3_A6EE_C631_1A63L,
        /* -200 */ 0xC3F4_90AA_77BD_60FCL,
        /* -199 */ 0xF4F1_B4D5_15AC_B93BL,
        /* -198 */ 0x9917_1105_2D8B_F3C5L,
        /* -197 */ 0xBF5C_D546_78EE_F0B6L,
        /* -196 */ 0xEF34_0A98_172A_ACE4L,
        /* -195 */ 0x9580_869F_0E7A_AC0EL,
        /* -194 */ 0xBAE0_A846_D219_5712L,
        /* -193 */ 0xE998_D258_869F_ACD7L,
        /* -192 */ 0x91FF_8377_5423_CC06L,
        /* -191 */ 0xB67F_6455_292C_BF08L,
        /* -190 */ 0xE41F_3D6A_7377_EECAL,
        /* -189 */ 0x8E93_8662_882A_F53EL,
        /* -188 */ 0xB238_67FB_2A35_B28DL,
        /* -187 */ 0xDEC6_81F9_F4C3_1F31L,
        /* -186 */ 0x8B3C_113C_38F9_F37EL,
        /* -185 */ 0xAE0B_158B_4738_705EL,
        /* -184 */ 0xD98D_DAEE_1906_8C76L,
        /* -183 */ 0x87F8_A8D4_CFA4_17C9L,
        /* -182 */ 0xA9F6_D30A_038D_1DBCL,
        /* -181 */ 0xD474_87CC_8470_652BL,
        /* -180 */ 0x84C8_D4DF_D2C6_3F3BL,
        /* -179 */ 0xA5FB_0A17_C777_CF09L,
        /* -178 */ 0xCF79_CC9D_B955_C2CCL,
        /* -177 */ 0x81AC_1FE2_93D5_99BFL,
        /* -176 */ 0xA217_27DB_38CB_002FL,
        /* -175 */ 0xCA9C_F1D2_06FD_C03BL,
        /* -174 */ 0xFD44_2E46_88BD_304AL,
        /* -173 */ 0x9E4A_9CEC_1576_3E2EL,
        /* -172 */ 0xC5DD_4427_1AD3_CDBAL,
        /* -171 */ 0xF754_9530_E188_C128L,
        /* -170 */ 0x9A94_DD3E_8CF5_78B9L,
        /* -169 */ 0xC13A_148E_3032_D6E7L,
        /* -168 */ 0xF188_99B1_BC3F_8CA1L,
        /* -167 */ 0x96F5_600F_15A7_B7E5L,
        /* -166 */ 0xBCB2_B812_DB11_A5DEL,
        /* -165 */ 0xEBDF_6617_91D6_0F56L,
        /* -164 */ 0x936B_9FCE_BB25_C995L,
        /* -163 */ 0xB846_87C2_69EF_3BFBL,
        /* -162 */ 0xE658_29B3_046B_0AFAL,
        /* -161 */ 0x8FF7_1A0F_E2C2_E6DCL,
        /* -160 */ 0xB3F4_E093_DB73_A093L,
        /* -159 */ 0xE0F2_18B8_D250_88B8L,
        /* -158 */ 0x8C97_4F73_8372_5573L,
        /* -157 */ 0xAFBD_2350_644E_EACFL,
        /* -156 */ 0xDBAC_6C24_7D62_A583L,
        /* -155 */ 0x894B_C396_CE5D_A772L,
        /* -154 */ 0xAB9E_B47C_81F5_114FL,
        /* -153 */ 0xD686_619B_A272_55A2L,
        /* -152 */ 0x8613_FD01_4587_7585L,
        /* -151 */ 0xA798_FC41_96E9_52E7L,
        /* -150 */ 0xD17F_3B51_FCA3_A7A0L,
        /* -149 */ 0x82EF_8513_3DE6_48C4L,
        /* -148 */ 0xA3AB_6658_0D5F_DAF5L,
        /* -147 */ 0xCC96_3FEE_10B7_D1B3L,
        /* -146 */ 0xFFBB_CFE9_94E5_C61FL,
        /* -145 */ 0x9FD5_61F1_FD0F_9BD3L,
        /* -144 */ 0xC7CA_BA6E_7C53_82C8L,
        /* -143 */ 0xF9BD_690A_1B68_637BL,
        /* -142 */ 0x9C16_61A6_5121_3E2DL,
        /* -141 */ 0xC31B_FA0F_E569_8DB8L,
        /* -140 */ 0xF3E2_F893_DEC3_F126L,
        /* -139 */ 0x986D_DB5C_6B3A_76B7L,
        /* -138 */ 0xBE89_5233_8609_1465L,
        /* -137 */ 0xEE2B_A6C0_678B_597FL,
        /* -136 */ 0x94DB_4838_40B7_17EFL,
        /* -135 */ 0xBA12_1A46_50E4_DDEBL,
        /* -134 */ 0xE896_A0D7_E51E_1566L,
        /* -133 */ 0x915E_2486_EF32_CD60L,
        /* -132 */ 0xB5B5_ADA8_AAFF_80B8L,
        /* -131 */ 0xE323_1912_D5BF_60E6L,
        /* -130 */ 0x8DF5_EFAB_C597_9C8FL,
        /* -129 */ 0xB173_6B96_B6FD_83B3L,
        /* -128 */ 0xDDD0_467C_64BC_E4A0L,
        /* -127 */ 0x8AA2_2C0D_BEF6_0EE4L,
        /* -126 */ 0xAD4A_B711_2EB3_929DL,
        /* -125 */ 0xD89D_64D5_7A60_7744L,
        /* -124 */ 0x8762_5F05_6C7C_4A8BL,
        /* -123 */ 0xA93A_F6C6_C79B_5D2DL,
        /* -122 */ 0xD389_B478_7982_3479L,
        /* -121 */ 0x8436_10CB_4BF1_60CBL,
        /* -120 */ 0xA543_94FE_1EED_B8FEL,
        /* -119 */ 0xCE94_7A3D_A6A9_273EL,
        /* -118 */ 0x811C_CC66_8829_B887L,
        /* -117 */ 0xA163_FF80_2A34_26A8L,
        /* -116 */ 0xC9BC_FF60_34C1_3052L,
        /* -115 */ 0xFC2C_3F38_41F1_7C67L,
        /* -114 */ 0x9D9B_A783_2936_EDC0L,
        /* -113 */ 0xC502_9163_F384_A931L,
        /* -112 */ 0xF643_35BC_F065_D37DL,
        /* -111 */ 0x99EA_0196_163F_A42EL,
        /* -110 */ 0xC064_81FB_9BCF_8D39L,
        /* -109 */ 0xF07D_A27A_82C3_7088L,
        /* -108 */ 0x964E_858C_91BA_2655L,
        /* -107 */ 0xBBE2_26EF_B628_AFEAL,
        /* -106 */ 0xEADA_B0AB_A3B2_DBE5L,
        /* -105 */ 0x92C8_AE6B_464F_C96FL,
        /* -104 */ 0xB77A_DA06_17E3_BBCBL,
        /* -103 */ 0xE559_9087_9DDC_AABDL,
        /* -102 */ 0x8F57_FA54_C2A9_EAB6L,
        /* -101 */ 0xB32D_F8E9_F354_6564L,
        /* -100 */ 0xDFF9_7724_7029_7EBDL,
        /*  -99 */ 0x8BFB_EA76_C619_EF36L,
        /*  -98 */ 0xAEFA_E514_77A0_6B03L,
        /*  -97 */ 0xDAB9_9E59_9588_85C4L,
        /*  -96 */ 0x88B4_02F7_FD75_539BL,
        /*  -95 */ 0xAAE1_03B5_FCD2_A881L,
        /*  -94 */ 0xD599_44A3_7C07_52A2L,
        /*  -93 */ 0x857F_CAE6_2D84_93A5L,
        /*  -92 */ 0xA6DF_BD9F_B8E5_B88EL,
        /*  -91 */ 0xD097_AD07_A71F_26B2L,
        /*  -90 */ 0x825E_CC24_C873_782FL,
        /*  -89 */ 0xA2F6_7F2D_FA90_563BL,
        /*  -88 */ 0xCBB4_1EF9_7934_6BCAL,
        /*  -87 */ 0xFEA1_26B7_D781_86BCL,
        /*  -86 */ 0x9F24_B832_E6B0_F436L,
        /*  -85 */ 0xC6ED_E63F_A05D_3143L,
        /*  -84 */ 0xF8A9_5FCF_8874_7D94L,
        /*  -83 */ 0x9B69_DBE1_B548_CE7CL,
        /*  -82 */ 0xC244_52DA_229B_021BL,
        /*  -81 */ 0xF2D5_6790_AB41_C2A2L,
        /*  -80 */ 0x97C5_60BA_6B09_19A5L,
        /*  -79 */ 0xBDB6_B8E9_05CB_600FL,
        /*  -78 */ 0xED24_6723_473E_3813L,
        /*  -77 */ 0x9436_C076_0C86_E30BL,
        /*  -76 */ 0xB944_7093_8FA8_9BCEL,
        /*  -75 */ 0xE795_8CB8_7392_C2C2L,
        /*  -74 */ 0x90BD_77F3_483B_B9B9L,
        /*  -73 */ 0xB4EC_D5F0_1A4A_A828L,
        /*  -72 */ 0xE228_0B6C_20DD_5232L,
        /*  -71 */ 0x8D59_0723_948A_535FL,
        /*  -70 */ 0xB0AF_48EC_79AC_E837L,
        /*  -69 */ 0xDCDB_1B27_9818_2244L,
        /*  -68 */ 0x8A08_F0F8_BF0F_156BL,
        /*  -67 */ 0xAC8B_2D36_EED2_DAC5L,
        /*  -66 */ 0xD7AD_F884_AA87_9177L,
        /*  -65 */ 0x86CC_BB52_EA94_BAEAL,
        /*  -64 */ 0xA87F_EA27_A539_E9A5L,
        /*  -63 */ 0xD29F_E4B1_8E88_640EL,
        /*  -62 */ 0x83A3_EEEE_F915_3E89L,
        /*  -61 */ 0xA48C_EAAA_B75A_8E2BL,
        /*  -60 */ 0xCDB0_2555_6531_31B6L,
        /*  -59 */ 0x808E_1755_5F3E_BF11L,
        /*  -58 */ 0xA0B1_9D2A_B70E_6ED6L,
        /*  -57 */ 0xC8DE_0475_64D2_0A8BL,
        /*  -56 */ 0xFB15_8592_BE06_8D2EL,
        /*  -55 */ 0x9CED_737B_B6C4_183DL,
        /*  -54 */ 0xC428_D05A_A475_1E4CL,
        /*  -53 */ 0xF533_0471_4D92_65DFL,
        /*  -52 */ 0x993F_E2C6_D07B_7FABL,
        /*  -51 */ 0xBF8F_DB78_849A_5F96L,
        /*  -50 */ 0xEF73_D256_A5C0_F77CL,
        /*  -49 */ 0x95A8_6376_2798_9AADL,
        /*  -48 */ 0xBB12_7C53_B17E_C159L,
        /*  -47 */ 0xE9D7_1B68_9DDE_71AFL,
        /*  -46 */ 0x9226_7121_62AB_070DL,
        /*  -45 */ 0xB6B0_0D69_BB55_C8D1L,
        /*  -44 */ 0xE45C_10C4_2A2B_3B05L,
        /*  -43 */ 0x8EB9_8A7A_9A5B_04E3L,
        /*  -42 */ 0xB267_ED19_40F1_C61CL,
        /*  -41 */ 0xDF01_E85F_912E_37A3L,
        /*  -40 */ 0x8B61_313B_BABC_E2C6L,
        /*  -39 */ 0xAE39_7D8A_A96C_1B77L,
        /*  -38 */ 0xD9C7_DCED_53C7_2255L,
        /*  -37 */ 0x881C_EA14_545C_7575L,
        /*  -36 */ 0xAA24_2499_6973_92D2L,
        /*  -35 */ 0xD4AD_2DBF_C3D0_7787L,
        /*  -34 */ 0x84EC_3C97_DA62_4AB4L,
        /*  -33 */ 0xA627_4BBD_D0FA_DD61L,
        /*  -32 */ 0xCFB1_1EAD_4539_94BAL,
        /*  -31 */ 0x81CE_B32C_4B43_FCF4L,
        /*  -30 */ 0xA242_5FF7_5E14_FC31L,
        /*  -29 */ 0xCAD2_F7F5_359A_3B3EL,
        /*  -28 */ 0xFD87_B5F2_8300_CA0DL,
        /*  -27 */ 0x9E74_D1B7_91E0_7E48L,
        /*  -26 */ 0xC612_0625_7658_9DDAL,
        /*  -25 */ 0xF796_87AE_D3EE_C551L,
        /*  -24 */ 0x9ABE_14CD_4475_3B52L,
        /*  -23 */ 0xC16D_9A00_9592_8A27L,
        /*  -22 */ 0xF1C9_0080_BAF7_2CB1L,
        /*  -21 */ 0x971D_A050_74DA_7BEEL,
        /*  -20 */ 0xBCE5_0864_9211_1AEAL,
        /*  -19 */ 0xEC1E_4A7D_B695_61A5L,
        /*  -18 */ 0x9392_EE8E_921D_5D07L,
        /*  -17 */ 0xB877_AA32_36A4_B449L,
        /*  -16 */ 0xE695_94BE_C44D_E15BL,
        /*  -15 */ 0x901D_7CF7_3AB0_ACD9L,
        /*  -14 */ 0xB424_DC35_095C_D80FL,
        /*  -13 */ 0xE12E_1342_4BB4_0E13L,
        /*  -12 */ 0x8CBC_CC09_6F50_88CBL,
        /*  -11 */ 0xAFEB_FF0B_CB24_AAFEL,
        /*  -10 */ 0xDBE6_FECE_BDED_D5BEL,
        /*   -9 */ 0x8970_5F41_36B4_A597L,
        /*   -8 */ 0xABCC_7711_8461_CEFCL,
        /*   -7 */ 0xD6BF_94D5_E57A_42BCL,
        /*   -6 */ 0x8637_BD05_AF6C_69B5L,
        /*   -5 */ 0xA7C5_AC47_1B47_8423L,
        /*   -4 */ 0xD1B7_1758_E219_652BL,
        /*   -3 */ 0x8312_6E97_8D4F_DF3BL,
        /*   -2 */ 0xA3D7_0A3D_70A3_D70AL,
        /*   -1 */ 0xCCCC_CCCC_CCCC_CCCCL,
        /*    0 */ 0x8000_0000_0000_0000L,
        /*    1 */ 0xA000_0000_0000_0000L,
        /*    2 */ 0xC800_0000_0000_0000L,
        /*    3 */ 0xFA00_0000_0000_0000L,
        /*    4 */ 0x9C40_0000_0000_0000L,
        /*    5 */ 0xC350_0000_0000_0000L,
        /*    6 */ 0xF424_0000_0000_0000L,
        /*    7 */ 0x9896_8000_0000_0000L,
        /*    8 */ 0xBEBC_2000_0000_0000L,
        /*    9 */ 0xEE6B_2800_0000_0000L,
        /*   10 */ 0x9502_F900_0000_0000L,
        /*   11 */ 0xBA43_B740_0000_0000L,
        /*   12 */ 0xE8D4_A510_0000_0000L,
        /*   13 */ 0x9184_E72A_0000_0000L,
        /*   14 */ 0xB5E6_20F4_8000_0000L,
        /*   15 */ 0xE35F_A931_A000_0000L,
        /*   16 */ 0x8E1B_C9BF_0400_0000L,
        /*   17 */ 0xB1A2_BC2E_C500_0000L,
        /*   18 */ 0xDE0B_6B3A_7640_0000L,
        /*   19 */ 0x8AC7_2304_89E8_0000L,
        /*   20 */ 0xAD78_EBC5_AC62_0000L,
        /*   21 */ 0xD8D7_26B7_177A_8000L,
        /*   22 */ 0x8786_7832_6EAC_9000L,
        /*   23 */ 0xA968_163F_0A57_B400L,
        /*   24 */ 0xD3C2_1BCE_CCED_A100L,
        /*   25 */ 0x8459_5161_4014_84A0L,
        /*   26 */ 0xA56F_A5B9_9019_A5C8L,
        /*   27 */ 0xCECB_8F27_F420_0F3AL,
        /*   28 */ 0x813F_3978_F894_0984L,
        /*   29 */ 0xA18F_07D7_36B9_0BE5L,
        /*   30 */ 0xC9F2_C9CD_0467_4EDEL,
        /*   31 */ 0xFC6F_7C40_4581_2296L,
        /*   32 */ 0x9DC5_ADA8_2B70_B59DL,
        /*   33 */ 0xC537_1912_364C_E305L,
        /*   34 */ 0xF684_DF56_C3E0_1BC6L,
        /*   35 */ 0x9A13_0B96_3A6C_115CL,
        /*   36 */ 0xC097_CE7B_C907_15B3L,
        /*   37 */ 0xF0BD_C21A_BB48_DB20L,
        /*   38 */ 0x9676_9950_B50D_88F4L,
        /*   39 */ 0xBC14_3FA4_E250_EB31L,
        /*   40 */ 0xEB19_4F8E_1AE5_25FDL,
        /*   41 */ 0x92EF_D1B8_D0CF_37BEL,
        /*   42 */ 0xB7AB_C627_0503_05ADL,
        /*   43 */ 0xE596_B7B0_C643_C719L,
        /*   44 */ 0x8F7E_32CE_7BEA_5C6FL,
        /*   45 */ 0xB35D_BF82_1AE4_F38BL,
        /*   46 */ 0xE035_2F62_A19E_306EL,
        /*   47 */ 0x8C21_3D9D_A502_DE45L,
        /*   48 */ 0xAF29_8D05_0E43_95D6L,
        /*   49 */ 0xDAF3_F046_51D4_7B4CL,
        /*   50 */ 0x88D8_762B_F324_CD0FL,
        /*   51 */ 0xAB0E_93B6_EFEE_0053L,
        /*   52 */ 0xD5D2_38A4_ABE9_8068L,
        /*   53 */ 0x85A3_6366_EB71_F041L,
        /*   54 */ 0xA70C_3C40_A64E_6C51L,
        /*   55 */ 0xD0CF_4B50_CFE2_0765L,
        /*   56 */ 0x8281_8F12_81ED_449FL,
        /*   57 */ 0xA321_F2D7_2268_95C7L,
        /*   58 */ 0xCBEA_6F8C_EB02_BB39L,
        /*   59 */ 0xFEE5_0B70_25C3_6A08L,
        /*   60 */ 0x9F4F_2726_179A_2245L,
        /*   61 */ 0xC722_F0EF_9D80_AAD6L,
        /*   62 */ 0xF8EB_AD2B_84E0_D58BL,
        /*   63 */ 0x9B93_4C3B_330C_8577L,
        /*   64 */ 0xC278_1F49_FFCF_A6D5L,
        /*   65 */ 0xF316_271C_7FC3_908AL,
        /*   66 */ 0x97ED_D871_CFDA_3A56L,
        /*   67 */ 0xBDE9_4E8E_43D0_C8ECL,
        /*   68 */ 0xED63_A231_D4C4_FB27L,
        /*   69 */ 0x945E_455F_24FB_1CF8L,
        /*   70 */ 0xB975_D6B6_EE39_E436L,
        /*   71 */ 0xE7D3_4C64_A9C8_5D44L,
        /*   72 */ 0x90E4_0FBE_EA1D_3A4AL,
        /*   73 */ 0xB51D_13AE_A4A4_88DDL,
        /*   74 */ 0xE264_589A_4DCD_AB14L,
        /*   75 */ 0x8D7E_B760_70A0_8AECL,
        /*   76 */ 0xB0DE_6538_8CC8_ADA8L,
        /*   77 */ 0xDD15_FE86_AFFA_D912L,
        /*   78 */ 0x8A2D_BF14_2DFC_C7ABL,
        /*   79 */ 0xACB9_2ED9_397B_F996L,
        /*   80 */ 0xD7E7_7A8F_87DA_F7FBL,
        /*   81 */ 0x86F0_AC99_B4E8_DAFDL,
        /*   82 */ 0xA8AC_D7C0_2223_11BCL,
        /*   83 */ 0xD2D8_0DB0_2AAB_D62BL,
        /*   84 */ 0x83C7_088E_1AAB_65DBL,
        /*   85 */ 0xA4B8_CAB1_A156_3F52L,
        /*   86 */ 0xCDE6_FD5E_09AB_CF26L,
        /*   87 */ 0x80B0_5E5A_C60B_6178L,
        /*   88 */ 0xA0DC_75F1_778E_39D6L,
        /*   89 */ 0xC913_936D_D571_C84CL,
        /*   90 */ 0xFB58_7849_4ACE_3A5FL,
        /*   91 */ 0x9D17_4B2D_CEC0_E47BL,
        /*   92 */ 0xC45D_1DF9_4271_1D9AL,
        /*   93 */ 0xF574_6577_930D_6500L,
        /*   94 */ 0x9968_BF6A_BBE8_5F20L,
        /*   95 */ 0xBFC2_EF45_6AE2_76E8L,
        /*   96 */ 0xEFB3_AB16_C59B_14A2L,
        /*   97 */ 0x95D0_4AEE_3B80_ECE5L,
        /*   98 */ 0xBB44_5DA9_CA61_281FL,
        /*   99 */ 0xEA15_7514_3CF9_7226L,
        /*  100 */ 0x924D_692C_A61B_E758L,
        /*  101 */ 0xB6E0_C377_CFA2_E12EL,
        /*  102 */ 0xE498_F455_C38B_997AL,
        /*  103 */ 0x8EDF_98B5_9A37_3FECL,
        /*  104 */ 0xB297_7EE3_00C5_0FE7L,
        /*  105 */ 0xDF3D_5E9B_C0F6_53E1L,
        /*  106 */ 0x8B86_5B21_5899_F46CL,
        /*  107 */ 0xAE67_F1E9_AEC0_7187L,
        /*  108 */ 0xDA01_EE64_1A70_8DE9L,
        /*  109 */ 0x8841_34FE_9086_58B2L,
        /*  110 */ 0xAA51_823E_34A7_EEDEL,
        /*  111 */ 0xD4E5_E2CD_C1D1_EA96L,
        /*  112 */ 0x850F_ADC0_9923_329EL,
        /*  113 */ 0xA653_9930_BF6B_FF45L,
        /*  114 */ 0xCFE8_7F7C_EF46_FF16L,
        /*  115 */ 0x81F1_4FAE_158C_5F6EL,
        /*  116 */ 0xA26D_A399_9AEF_7749L,
        /*  117 */ 0xCB09_0C80_01AB_551CL,
        /*  118 */ 0xFDCB_4FA0_0216_2A63L,
        /*  119 */ 0x9E9F_11C4_014D_DA7EL,
        /*  120 */ 0xC646_D635_01A1_511DL,
        /*  121 */ 0xF7D8_8BC2_4209_A565L,
        /*  122 */ 0x9AE7_5759_6946_075FL,
        /*  123 */ 0xC1A1_2D2F_C397_8937L,
        /*  124 */ 0xF209_787B_B47D_6B84L,
        /*  125 */ 0x9745_EB4D_50CE_6332L,
        /*  126 */ 0xBD17_6620_A501_FBFFL,
        /*  127 */ 0xEC5D_3FA8_CE42_7AFFL,
        /*  128 */ 0x93BA_47C9_80E9_8CDFL,
        /*  129 */ 0xB8A8_D9BB_E123_F017L,
        /*  130 */ 0xE6D3_102A_D96C_EC1DL,
        /*  131 */ 0x9043_EA1A_C7E4_1392L,
        /*  132 */ 0xB454_E4A1_79DD_1877L,
        /*  133 */ 0xE16A_1DC9_D854_5E94L,
        /*  134 */ 0x8CE2_529E_2734_BB1DL,
        /*  135 */ 0xB01A_E745_B101_E9E4L,
        /*  136 */ 0xDC21_A117_1D42_645DL,
        /*  137 */ 0x8995_04AE_7249_7EBAL,
        /*  138 */ 0xABFA_45DA_0EDB_DE69L,
        /*  139 */ 0xD6F8_D750_9292_D603L,
        /*  140 */ 0x865B_8692_5B9B_C5C2L,
        /*  141 */ 0xA7F2_6836_F282_B732L,
        /*  142 */ 0xD1EF_0244_AF23_64FFL,
        /*  143 */ 0x8335_616A_ED76_1F1FL,
        /*  144 */ 0xA402_B9C5_A8D3_A6E7L,
        /*  145 */ 0xCD03_6837_1308_90A1L,
        /*  146 */ 0x8022_2122_6BE5_5A64L,
        /*  147 */ 0xA02A_A96B_06DE_B0FDL,
        /*  148 */ 0xC835_53C5_C896_5D3DL,
        /*  149 */ 0xFA42_A8B7_3ABB_F48CL,
        /*  150 */ 0x9C69_A972_84B5_78D7L,
        /*  151 */ 0xC384_13CF_25E2_D70DL,
        /*  152 */ 0xF465_18C2_EF5B_8CD1L,
        /*  153 */ 0x98BF_2F79_D599_3802L,
        /*  154 */ 0xBEEE_FB58_4AFF_8603L,
        /*  155 */ 0xEEAA_BA2E_5DBF_6784L,
        /*  156 */ 0x952A_B45C_FA97_A0B2L,
        /*  157 */ 0xBA75_6174_393D_88DFL,
        /*  158 */ 0xE912_B9D1_478C_EB17L,
        /*  159 */ 0x91AB_B422_CCB8_12EEL,
        /*  160 */ 0xB616_A12B_7FE6_17AAL,
        /*  161 */ 0xE39C_4976_5FDF_9D94L,
        /*  162 */ 0x8E41_ADE9_FBEB_C27DL,
        /*  163 */ 0xB1D2_1964_7AE6_B31CL,
        /*  164 */ 0xDE46_9FBD_99A0_5FE3L,
        /*  165 */ 0x8AEC_23D6_8004_3BEEL,
        /*  166 */ 0xADA7_2CCC_2005_4AE9L,
        /*  167 */ 0xD910_F7FF_2806_9DA4L,
        /*  168 */ 0x87AA_9AFF_7904_2286L,
        /*  169 */ 0xA995_41BF_5745_2B28L,
        /*  170 */ 0xD3FA_922F_2D16_75F2L,
        /*  171 */ 0x847C_9B5D_7C2E_09B7L,
        /*  172 */ 0xA59B_C234_DB39_8C25L,
        /*  173 */ 0xCF02_B2C2_1207_EF2EL,
        /*  174 */ 0x8161_AFB9_4B44_F57DL,
        /*  175 */ 0xA1BA_1BA7_9E16_32DCL,
        /*  176 */ 0xCA28_A291_859B_BF93L,
        /*  177 */ 0xFCB2_CB35_E702_AF78L,
        /*  178 */ 0x9DEF_BF01_B061_ADABL,
        /*  179 */ 0xC56B_AEC2_1C7A_1916L,
        /*  180 */ 0xF6C6_9A72_A398_9F5BL,
        /*  181 */ 0x9A3C_2087_A63F_6399L,
        /*  182 */ 0xC0CB_28A9_8FCF_3C7FL,
        /*  183 */ 0xF0FD_F2D3_F3C3_0B9FL,
        /*  184 */ 0x969E_B7C4_7859_E743L,
        /*  185 */ 0xBC46_65B5_9670_6114L,
        /*  186 */ 0xEB57_FF22_FC0C_7959L,
        /*  187 */ 0x9316_FF75_DD87_CBD8L,
        /*  188 */ 0xB7DC_BF53_54E9_BECEL,
        /*  189 */ 0xE5D3_EF28_2A24_2E81L,
        /*  190 */ 0x8FA4_7579_1A56_9D10L,
        /*  191 */ 0xB38D_92D7_60EC_4455L,
        /*  192 */ 0xE070_F78D_3927_556AL,
        /*  193 */ 0x8C46_9AB8_43B8_9562L,
        /*  194 */ 0xAF58_4166_54A6_BABBL,
        /*  195 */ 0xDB2E_51BF_E9D0_696AL,
        /*  196 */ 0x88FC_F317_F222_41E2L,
        /*  197 */ 0xAB3C_2FDD_EEAA_D25AL,
        /*  198 */ 0xD60B_3BD5_6A55_86F1L,
        /*  199 */ 0x85C7_0565_6275_7456L,
        /*  200 */ 0xA738_C6BE_BB12_D16CL,
        /*  201 */ 0xD106_F86E_69D7_85C7L,
        /*  202 */ 0x82A4_5B45_0226_B39CL,
        /*  203 */ 0xA34D_7216_42B0_6084L,
        /*  204 */ 0xCC20_CE9B_D35C_78A5L,
        /*  205 */ 0xFF29_0242_C833_96CEL,
        /*  206 */ 0x9F79_A169_BD20_3E41L,
        /*  207 */ 0xC758_09C4_2C68_4DD1L,
        /*  208 */ 0xF92E_0C35_3782_6145L,
        /*  209 */ 0x9BBC_C7A1_42B1_7CCBL,
        /*  210 */ 0xC2AB_F989_935D_DBFEL,
        /*  211 */ 0xF356_F7EB_F835_52FEL,
        /*  212 */ 0x9816_5AF3_7B21_53DEL,
        /*  213 */ 0xBE1B_F1B0_59E9_A8D6L,
        /*  214 */ 0xEDA2_EE1C_7064_130CL,
        /*  215 */ 0x9485_D4D1_C63E_8BE7L,
        /*  216 */ 0xB9A7_4A06_37CE_2EE1L,
        /*  217 */ 0xE811_1C87_C5C1_BA99L,
        /*  218 */ 0x910A_B1D4_DB99_14A0L,
        /*  219 */ 0xB54D_5E4A_127F_59C8L,
        /*  220 */ 0xE2A0_B5DC_971F_303AL,
        /*  221 */ 0x8DA4_71A9_DE73_7E24L,
        /*  222 */ 0xB10D_8E14_5610_5DADL,
        /*  223 */ 0xDD50_F199_6B94_7518L,
        /*  224 */ 0x8A52_96FF_E33C_C92FL,
        /*  225 */ 0xACE7_3CBF_DC0B_FB7BL,
        /*  226 */ 0xD821_0BEF_D30E_FA5AL,
        /*  227 */ 0x8714_A775_E3E9_5C78L,
        /*  228 */ 0xA8D9_D153_5CE3_B396L,
        /*  229 */ 0xD310_45A8_341C_A07CL,
        /*  230 */ 0x83EA_2B89_2091_E44DL,
        /*  231 */ 0xA4E4_B66B_68B6_5D60L,
        /*  232 */ 0xCE1D_E406_42E3_F4B9L,
        /*  233 */ 0x80D2_AE83_E9CE_78F3L,
        /*  234 */ 0xA107_5A24_E442_1730L,
        /*  235 */ 0xC949_30AE_1D52_9CFCL,
        /*  236 */ 0xFB9B_7CD9_A4A7_443CL,
        /*  237 */ 0x9D41_2E08_06E8_8AA5L,
        /*  238 */ 0xC491_798A_08A2_AD4EL,
        /*  239 */ 0xF5B5_D7EC_8ACB_58A2L,
        /*  240 */ 0x9991_A6F3_D6BF_1765L,
        /*  241 */ 0xBFF6_10B0_CC6E_DD3FL,
        /*  242 */ 0xEFF3_94DC_FF8A_948EL,
        /*  243 */ 0x95F8_3D0A_1FB6_9CD9L,
        /*  244 */ 0xBB76_4C4C_A7A4_440FL,
        /*  245 */ 0xEA53_DF5F_D18D_5513L,
        /*  246 */ 0x9274_6B9B_E2F8_552CL,
        /*  247 */ 0xB711_8682_DBB6_6A77L,
        /*  248 */ 0xE4D5_E823_92A4_0515L,
        /*  249 */ 0x8F05_B116_3BA6_832DL,
        /*  250 */ 0xB2C7_1D5B_CA90_23F8L,
        /*  251 */ 0xDF78_E4B2_BD34_2CF6L,
        /*  252 */ 0x8BAB_8EEF_B640_9C1AL,
        /*  253 */ 0xAE96_72AB_A3D0_C320L,
        /*  254 */ 0xDA3C_0F56_8CC4_F3E8L,
        /*  255 */ 0x8865_8996_17FB_1871L,
        /*  256 */ 0xAA7E_EBFB_9DF9_DE8DL,
        /*  257 */ 0xD51E_A6FA_8578_5631L,
        /*  258 */ 0x8533_285C_936B_35DEL,
        /*  259 */ 0xA67F_F273_B846_0356L,
        /*  260 */ 0xD01F_EF10_A657_842CL,
        /*  261 */ 0x8213_F56A_67F6_B29BL,
        /*  262 */ 0xA298_F2C5_01F4_5F42L,
        /*  263 */ 0xCB3F_2F76_4271_7713L,
        /*  264 */ 0xFE0E_FB53_D30D_D4D7L,
        /*  265 */ 0x9EC9_5D14_63E8_A506L,
        /*  266 */ 0xC67B_B459_7CE2_CE48L,
        /*  267 */ 0xF81A_A16F_DC1B_81DAL,
        /*  268 */ 0x9B10_A4E5_E991_3128L,
        /*  269 */ 0xC1D4_CE1F_63F5_7D72L,
        /*  270 */ 0xF24A_01A7_3CF2_DCCFL,
        /*  271 */ 0x976E_4108_8617_CA01L,
        /*  272 */ 0xBD49_D14A_A79D_BC82L,
        /*  273 */ 0xEC9C_459D_5185_2BA2L,
        /*  274 */ 0x93E1_AB82_52F3_3B45L,
        /*  275 */ 0xB8DA_1662_E7B0_0A17L,
        /*  276 */ 0xE710_9BFB_A19C_0C9DL,
        /*  277 */ 0x906A_617D_4501_87E2L,
        /*  278 */ 0xB484_F9DC_9641_E9DAL,
        /*  279 */ 0xE1A6_3853_BBD2_6451L,
        /*  280 */ 0x8D07_E334_5563_7EB2L,
        /*  281 */ 0xB049_DC01_6ABC_5E5FL,
        /*  282 */ 0xDC5C_5301_C56B_75F7L,
        /*  283 */ 0x89B9_B3E1_1B63_29BAL,
        /*  284 */ 0xAC28_20D9_623B_F429L,
        /*  285 */ 0xD732_290F_BACA_F133L,
        /*  286 */ 0x867F_59A9_D4BE_D6C0L,
        /*  287 */ 0xA81F_3014_49EE_8C70L,
        /*  288 */ 0xD226_FC19_5C6A_2F8CL,
        /*  289 */ 0x8358_5D8F_D9C2_5DB7L,
        /*  290 */ 0xA42E_74F3_D032_F525L,
        /*  291 */ 0xCD3A_1230_C43F_B26FL,
        /*  292 */ 0x8044_4B5E_7AA7_CF85L,
        /*  293 */ 0xA055_5E36_1951_C366L,
        /*  294 */ 0xC86A_B5C3_9FA6_3440L,
        /*  295 */ 0xFA85_6334_878F_C150L,
        /*  296 */ 0x9C93_5E00_D4B9_D8D2L,
        /*  297 */ 0xC3B8_3581_09E8_4F07L,
        /*  298 */ 0xF4A6_42E1_4C62_62C8L,
        /*  299 */ 0x98E7_E9CC_CFBD_7DBDL,
        /*  300 */ 0xBF21_E440_03AC_DD2CL,
        /*  301 */ 0xEEEA_5D50_0498_1478L,
        /*  302 */ 0x9552_7A52_02DF_0CCBL,
        /*  303 */ 0xBAA7_18E6_8396_CFFDL,
        /*  304 */ 0xE950_DF20_247C_83FDL,
        /*  305 */ 0x91D2_8B74_16CD_D27EL,
        /*  306 */ 0xB647_2E51_1C81_471DL,
        /*  307 */ 0xE3D8_F9E5_63A1_98E5L,
        /*  308 */ 0x8E67_9C2F_5E44_FF8FL,
        /*  309 */ 0xB201_833B_35D6_3F73L,
        /*  310 */ 0xDE81_E40A_034B_CF4FL,
        /*  311 */ 0x8B11_2E86_420F_6191L,
        /*  312 */ 0xADD5_7A27_D293_39F6L,
        /*  313 */ 0xD94A_D8B1_C738_0874L,
        /*  314 */ 0x87CE_C76F_1C83_0548L,
        /*  315 */ 0xA9C2_794A_E3A3_C69AL,
        /*  316 */ 0xD433_179D_9C8C_B841L,
        /*  317 */ 0x849F_EEC2_81D7_F328L,
        /*  318 */ 0xA5C7_EA73_224D_EFF3L,
        /*  319 */ 0xCF39_E50F_EAE1_6BEFL,
        /*  320 */ 0x8184_2F29_F2CC_E375L,
        /*  321 */ 0xA1E5_3AF4_6F80_1C53L,
        /*  322 */ 0xCA5E_89B1_8B60_2368L,
        /*  323 */ 0xFCF6_2C1D_EE38_2C42L,
        /*  324 */ 0x9E19_DB92_B4E3_1BA9L,
    };

}

-------- math.DoubleToDecimal.java

/*
 * Copyright (c) 2018, Raffaello Giulietti. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 * This particular file is subject to the "Classpath" exception as provided
 * in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 */

package math;

import static java.lang.Double.*;
import static java.lang.Math.max;
import static java.lang.Long.numberOfLeadingZeros;
import static math.MathUtils.*;
import static math.DoubleToDecimal.Double.*;
import static math.Natural.valueOfShiftLeft;
import static math.Powers.*;

/**
 * This class exposes a method to render a {@code double} as a string.
 */
final public class DoubleToDecimal {
    /*
    For full details of the logic in this and the other supporting classes,
    search the web for
        d6b9e38fbe27f199d27e19f25acc26452e7e2ece
    and check that the title reads
        "Rendering doubles in Java"
     */

    /**
     * Exposes some constants related to the IEEE 754-2008 breakdown of
     * {@code double}s and some extractors suited for finite positive
values.
     *
     * <p>A finite positive {@code double} <i>v</i> has the form
     * <i>v</i> = <i>c</i>&#xb7;2<sup><i>q</i></sup>,
     * where integers <i>c</i>, <i>q</i> meet
     * <ul>
     * <li> either 2<sup>{@link #P}-1</sup> &#x2264; <i>c</i> &#x3c;
     * 2<sup>{@link #P}</sup> and {@link #Q_MIN} &#x2264; <i>q</i> &#x2264;
     * {@link #Q_MAX} (normal <i>v</i>)
     * <li> or 0 &#x3c; <i>c</i> &#x3c; 2<sup>{@link #P}-1</sup> and
     * <i>c</i> = {@link #Q_MIN} (subnormal <i>v</i>)
     * </ul>
     */
    static final class Double {

        /**
         * Precision of normal values in bits.
         */
        static final int P = 53;

        /**
         * Length in bits of the exponent field.
         */
        static final int W = (java.lang.Double.SIZE - 1) - (P - 1);

        /**
         * Minimum value of the exponent.
         */
        static final int Q_MIN = (-1 << W - 1) - P + 3;

        /**
         * Maximum value of the exponent.
         */
        static final int Q_MAX = (1 << W - 1) - P;

        /**
         * Minimum value of the coefficient of a normal value.
         */
        static final long C_MIN = 1L << P - 1;

        /**
         * Maximum value of the coefficient of a normal value.
         */
        static final long C_MAX = (1L << P) - 1;

        /**
         * H = min {n integer | 10^(n-1) > 2^P}
         */
        static final int H = 17;

        /**
         * G = max {n integer | 2^(P-1) > 10^n}
         */
        static final int G = 15;

        /**
         * The integer <i>e</i> such that
         * 10<sup><i>e</i>-1</sup> &#x2264; {@link
java.lang.Double#MIN_VALUE}
         * &#x3c; 10<sup><i>e</i></sup>.
         */
        static final int E_MIN_VALUE = -323;

        /**
         * The integer <i>e</i> such that
         * 10<sup><i>e</i>-1</sup> &#x2264; {@link
java.lang.Double#MIN_NORMAL}
         * &#x3c; 10<sup><i>e</i></sup>.
         */
        static final int E_MIN_NORMAL = -307;

        /**
         * The integer <i>e</i> such that
         * 10<sup><i>e</i>-1</sup> &#x2264; {@link
java.lang.Double#MAX_VALUE}
         * &#x3c; 10<sup><i>e</i></sup>.
         */
        static final int E_MAX_VALUE = 309;

        // Mask to extract the IEEE 754-2008 biased exponent.
        private static final int BQ_MASK = (1 << W) - 1;

        // Mask to extract the IEEE 754-2008 fraction bits.
        private static final long T_MASK = (1L << P - 1) - 1;

        // Constants for the computation of roundCeilPow10()
        private static final int D = Long.SIZE - P;
        private static final long CEIL_EPS = (1L << D) - 1;
        private static final int ORD_2_MIN_NORMAL = Q_MIN + P;

        private Double() {
        }

        private static int bq(long bits) {
            return (int) (bits >>> P - 1) & BQ_MASK;
        }

        /**
         * Given the {@code bits} of a finite positive {@code double},
         * returns <i>q</i> described in {@link java.lang.Double}.
         */
        static int q(long bits) {
            int bq = bq(bits);
            if (bq > 0) {
                return Q_MIN - 1 + bq;
            }
            return Q_MIN;
        }

        /**
         * Given the {@code bits} of a finite positive {@code double},
         * returns <i>c</i> described in {@link java.lang.Double}.
         */
        static long c(long bits) {
            int bq = bq(bits);
            long t = bits & T_MASK;
            if (bq > 0) {
                return C_MIN | t;
            }
            return t;
        }

        private static int ord2(int q, long c) {
            // Fast path for the normal case.
            if (c >= C_MIN) {
                return P + q;
            }
            return Q_MIN + Long.SIZE - numberOfLeadingZeros(c);
        }

        /**
         * For finite positive {@code v}, returns the integer <i>e</i>
such that
         * 2<sup><i>e</i>-1</sup> &#x2264; {@code v} &#x3c;
         * 2<sup><i>e</i></sup>.
         */
        private static int ord2(double v) {
            long bits = java.lang.Double.doubleToRawLongBits(v);
            return ord2(q(bits), c(bits));
        }

        /**
         * For finite positive {@code v}, returns the integer <i>e</i>
such that
         * 10<sup><i>e</i>-1</sup> &#x2264; {@code v} &#x3c;
         * 10<sup><i>e</i></sup>.
         */
        static int ord10(double v) {
            int ep = ord10pow2(ord2(v)) - 1;
            if (v < roundCeilPow10(ep)) return ep;
            return ep + 1;
        }

        // Returns the smallest double v such that 10^e <= v.
        private static double roundCeilPow10(int e) {
            int e2 = ord2pow10(e);
            if (e2 >= ORD_2_MIN_NORMAL) {
                long c = (floorPow10d(e) + CEIL_EPS) >>> D;
                int q = e2 - P;
                long bits = (long) (q - (Q_MIN - 1)) << P - 1 | c & T_MASK;
                return java.lang.Double.longBitsToDouble(bits);
            }
            int d = ORD_2_MIN_NORMAL + D - e2;
            if (d < Long.SIZE) {
                long c = (floorPow10d(e) + (1L << d) - 1) >>> d;
                return java.lang.Double.longBitsToDouble(c);
            }
            return java.lang.Double.MIN_VALUE;
        }

    }

    // used in the left-to-right extraction of the digits
    private static final int LTR = 28;
    private static final int MASK_LTR = (1 << LTR) - 1;

    // MAX_SIGNIFICAND = 10^H
    private static final long MAX_SIGNIFICAND = 100_000_000_000_000_000L;

    // The additional precision, used in reduced()
    private static final int D = Long.SIZE - P;

    // for thread-safety, each thread gets its own instance of this class
    private static final ThreadLocal<DoubleToDecimal> threadLocal =
            ThreadLocal.withInitial(DoubleToDecimal::new);

    /*
    Given finite positive double v, there are two breakdowns:
        v = c * 2^q, as described in DoubleToDecimal.Double
        v = f * 10^e, with 0.1 <= f < 1
    e, q, and c are kept in the following fields.
     */
    private int e;
    private int q;
    private long c;

    /*
    For the default IEEE round-to-closest rounding, lout = rout always
holds.
    However, two fields are kept for possible future extensions.
    Possible values are
        0, if the boundary of the rounding interval is included
        1, if the boundary of the rounding interval is excluded
     */
    private int lout; // left (closer to 0) boundary
    private int rout; // right (farther from 0) boundary

    /*
    Room for H digits, 3 exponent digits, 2 '-', 1 '.', 1 'E' = H + 7
    or for "-0.00" + H digits = H + 5
     */
    private final char[] buf = new char[H + 7];
    private int index; // index of rightmost valid character

    private DoubleToDecimal() {
    }

    /**
     * Returns a string rendering of the {@code double} argument.
     *
     * <p>The characters of the result are all drawn from the ASCII set.
     * <ul>
     *     <li> Any NaN, whether quiet or signaling, is rendered
symbolically
     *     as {@code "NaN"}, regardless of the sign bit.
     *     <li> The infinities +&#x221e; and -&#x221e; are rendered as
     *     {@code "Infinity"} and {@code "-Infinity"}, respectively.
     *     <li> The zeroes +0.0 and -0.0 are rendered as
     *     {@code "0.0"} and {@code "-0.0"}, respectively.
     *     <li> Otherwise {@code v} is finite and non-zero.
     *     It is rendered in two stages:
     *     <ul>
     *         <li> Selection of a decimal: A well-specified non-zero
decimal
     *         <i>d</i> is selected to represent {@code v}.
     *         <li> Formatting as a string: The decimal <i>d</i> is
formatted
     *         as a string, either in plain or in computerized scientific
     *         notation, depending on its value.
     *     </ul>
     * </ul>
     *
     * <p>A decimal <i>d</i> is said to have length <i>i</i> if it has
     * the form <i>d</i> = <i>c</i> &#xb7; 10<sup><i>q</i></sup>
     * for some integers <i>c</i> and <i>q</i> and if the decimal
expansion of
     * <i>c</i> consists of <i>i</i> digits. Note that if <i>d</i> has some
     * length, then it has any other greater length as well: grow
<i>c</i> by
     * appending trailing zeroes and decrease <i>q</i> accordingly.
     *
     * <p>Abstractly, the unique decimal <i>d</i> to represent {@code v}
     * is selected as follows:
     * <ul>
     *     <li>First, all decimals that round to {@code v} according to the
     *     usual round-to-closest rule of IEEE 754 floating-point arithmetic
     *     are tentatively selected, while the other are discarded.
     *     There is never the need to go beyond a length of 17.
     *     <li>Among these, only the ones that have the shortest possible
     *     length  not less than 2 are selected and the other are discarded.
     *     <li>Finally, among these, only the one closest to {@code v} is
     *     definitely selected: or if two are equally close to {@code
v}, the
     *     one whose least significant digit is even is definitely selected.
     * </ul>
     *
     * <p>The selected decimal <i>d</i> is then formatted as a string.
     * If <i>d</i> &#x3c; 0, the first character of the string is the sign
     * '{@code -}'. Then consider the absolute value and let
     * |<i>d</i>| = <i>m</i> &#xb7; 10<sup><i>k</i></sup>, for some unique
     * real <i>m</i> meeting 1 &#x2264; <i>m</i> < 10 and integer
<i>k</i>.
     * Further, let the decimal expansion of <i>m</i> be
     * <i>m</i><sub>1</sub>.<i>m</i><sub>2</sub>&#x2026;<!--
     * --><i>m</i><sub><i>i</i></sub>,
     * with <i>i</i> &#x2265; 1 and <i>m</i><sub><i>i</i></sub> &#x2260; 0.
     * <ul>
     *     <li>Case -3 &#x2264; k &#x3c; 0: |<i>d</i>| is formatted as
     *     0.0&#x2026;0<i>m</i><sub>1</sub>&#x2026;<!--
     *     --><i>m</i><sub><i>i</i></sub>,
     *     where there are exactly -<i>k</i> leading zeroes before
     *     <i>m</i><sub>1</sub>, including the zero before the decimal
point.
     *     For example, {@code "0.01234"}.
     *     <li>Case 0 &#x2264; <i>k</i> &#x3c; 7:
     *     <ul>
     *         <li>Subcase <i>i</i> &#x3c; <i>k</i> + 2:
     *         |<i>d</i>| is formatted as
     *         <i>m</i><sub>1</sub>&#x2026;<!--
     *         --><i>m</i><sub><i>i</i></sub>0&#x2026;0.0,
     *         where there are exactly <i>k</i> + 2 - <i>i</i> trailing
zeroes
     *         after <i>m</i><sub><i>i</i></sub>, including the zero after
     *         the decimal point.
     *         For example, {@code "1200.0"}.
     *         <li>Subcase <i>i</i> &#x2265; <i>k</i> + 2:
     *         |<i>d</i>| is formatted as
     *
<i>m</i><sub>1</sub>&#x2026;<i>m</i><sub><i>k</i>+1</sub>.<!--
     *         --><i>m</i><sub><i>k</i>+2</sub>&#x2026;<!--
     *         --><i>m</i><sub><i>i</i></sub>.
     *         For example, {@code "1234.567"}.
     *     </ul>
     *     <li>Case <i>k</i> &#x3c; -3 or <i>k</i> &#x2265; 7:
     *     computerized scientific notation is used to format |<i>d</i>|,
     *     by combining <i>m</i> and <i>k</i> separated by the exponent
     *     indicator '{@code E}'.
     *     <ul>
     *         <li>Subcase <i>i</i> = 1:
     *         |<i>d</i>| is formatted as
     *         <i>m</i><sub>1</sub>.0E<i>k</i>.
     *         For example, {@code "2.0E23"}.
     *         <li>Subcase <i>i</i> > 1:
     *         |<i>d</i>| is formatted as
     *         <i>m</i><sub>1</sub>.<i>m</i><sub>2</sub>&#x2026;<!--
     *         --><i>m</i><sub><i>i</i></sub>E<i>k</i>.
     *         For example, {@code "1.2345E-67"}.
     *     </ul>
     *     The exponent <i>k</i> is formatted as in
     *     {@link Integer#toString(int)}.
     *  </ul>
     *
     * @param  v the {@code double} to be rendered.
     * @return a string rendering of the argument.
     */
    public static String toString(double v) {
        return threadLocalInstance().toDecimal(v);
    }

    private static DoubleToDecimal threadLocalInstance() {
        return threadLocal.get();
    }

    private String toDecimal(double v) {
        // Get rid of NaNs, infinities and zeroes right at the beginning
        if (v != v) {
            return "NaN";
        }
        if (v == POSITIVE_INFINITY) {
            return "Infinity";
        }
        if (v == NEGATIVE_INFINITY) {
            return "-Infinity";
        }
        long bits = doubleToRawLongBits(v);
        if (bits == 0x0000_0000_0000_0000L) {
            return "0.0";
        }
        if (bits == 0x8000_0000_0000_0000L) {
            return "-0.0";
        }
        index = -1;
        if (bits < 0) {
            append('-');
            v = -v;
        }
        e = ord10(v);
        /*
        When v is an integer less than 10^9, a common case in practice,
        use a customized faster method.
         */
        long l = (long) v;
        if (l == v & l < 1_000_000_000L) {
            return integer(l);
        }
        q = q(bits);
        c = c(bits);
        lout = rout = (int) (c) & 0x1;
        /*
        The reduced() method assumes v is normal, i.e., has full
precision P,
        and that powers of 2 have unequally distant predecessor and
successor.
        MIN_NORMAL is normal and a power of 2 but its predecessor and
        its successor are equally close to it, so is excluded from
reduced().
        Note that reduced() might failover to full().
         */
        if (v > MIN_NORMAL) {
            return reduced();
        }
        return full();
    }

    private String integer(long l) {
        return toChars(l * pow10[H - 8 - e], e);
    }

    private String full() {
        long cb;
        int qb;
        long cbr;
        if (c != C_MIN | q == Q_MIN) {
            cb = c << 1;
            qb = q - 1;
            cbr = cb + 1;
        } else {
            cb = c << 2;
            qb = q - 2;
            cbr = cb + 2;
        }
        if (e <= H) {
            if (e - qb <= H) {
                return fullCaseM(qb, cb, cbr);
            }
            if (H - 3 <= e) {
                return fullSubcaseS(qb, cb, cbr);
            }
            int p = q > Q_MIN || c > C_MIN ?
                    P :
                    Long.SIZE - numberOfLeadingZeros(c - 1);
            int i = max(ord10pow2(p - 1) - 1, 2);
            return fullCaseXS(qb, cb, cbr, i);
        }
        if (qb - e <= 8 - H) {
            return fullSubcaseL(qb, cb, cbr);
        }
        return fullCaseXL(qb, cb, cbr);
    }

    private String fullCaseXS(int qb, long cb, long cb_r, int i) {
        Natural m = pow5(H - e);
        Natural vb = m.multiply(cb);
        Natural vbl = vb.subtract(m);
        Natural vbr = m.multiply(cb_r);
        int p = e - H - qb;
        long sbH = vb.shiftRight(p);
        for (int g = H - i; g >= 0; --g) {
            long di = pow10[g];
            long sbi = sbH - sbH % di;
            Natural ubi = valueOfShiftLeft(sbi, p);
            Natural wbi = valueOfShiftLeft(sbi + di, p);
            boolean uin = vbl.compareTo(ubi) + lout <= 0;
            boolean win = wbi.compareTo(vbr) + rout <= 0;
            if (uin & !win) {
                return toChars(sbi,  e);
            }
            if (!uin & win) {
                return toChars(sbi + di, e);
            }
            if (uin) {
                int cmp = vb.closerTo(ubi, wbi);
                if (cmp < 0 || cmp == 0 && (sbi / di & 0x1) == 0) {
                    return toChars(sbi, e);
                }
                return toChars(sbi + di,  e);
            }
        }
        throw new AssertionError("unreachable code");
    }

    private String fullSubcaseS(int qb, long cb, long cb_r) {
        long m = pow5[H - e];
        long vb = cb * m;
        long vbl = vb - m;
        long vbr = cb_r * m;
        int p = e - H - qb;
        long sbH = vb >> p;
        for (int g = H - G; g >= 0; --g) {
            long di = pow10(g);
            long sbi = sbH - sbH % di;
            long ubi = sbi << p;
            long wbi = sbi + di << p;
            boolean uin = vbl + lout <= ubi;
            boolean win = wbi + rout <= vbr;
            if (uin & !win) {
                return toChars(sbi,  e);
            }
            if (!uin & win) {
                return toChars(sbi + di, e);
            }
            if (uin) {
                int cmp = (int) (2 * vb - ubi - wbi);
                if (cmp < 0 || cmp == 0 && (sbi / di & 0x1) == 0) {
                    return toChars(sbi, e);
                }
                return toChars(sbi + di,  e);
            }
        }
        throw new AssertionError("unreachable code");
    }

    private String fullCaseM(int qb, long cb, long cb_r) {
        long m = pow5[H - e] << H - e + qb;
        long vb = cb * m;
        long vbl = vb - m;
        long vbr = cb_r * m;
        for (int g = H - G; g > 0; --g) {
            long di = pow10(g);
            long sbi = vb - vb % di;
            long tbi = sbi + di;
            boolean uin = vbl + lout <= sbi;
            boolean win = tbi + rout <= vbr;
            if (uin & !win) {
                return toChars(sbi,  e);
            }
            if (!uin & win) {
                return toChars(tbi, e);
            }
            if (uin) {
                int cmp = (int) (2 * vb - sbi - tbi);
                if (cmp < 0 || cmp == 0 && (vb / di & 0x1) == 0) {
                    return toChars(sbi, e);
                }
                return toChars(tbi,  e);
            }
        }
        /*
        The loop didn't produce a shorter result.
        The full sb_H = s_H = vb is needed. This is done outside the loop,
        as there's no need to check tb_H = t_H as well.
         */
        return toChars(vb, e);
    }

    private String fullSubcaseL(int qb, long cb, long cb_r) {
        int p = H - e + qb;
        long vb = cb << p;
        long vbl = cb - 1 << p;
        long vbr = cb_r << p;
        long m = pow5[e - H];
        long sbH = vb / m;
        for (int g = H - G; g >= 0; --g) {
            long di = pow10(g);
            long sbi = sbH - sbH % di;
            long ubi = sbi * m;
            long wbi = ubi + (pow5[e - H + g] << g);
            boolean uin = vbl + lout <= ubi;
            boolean win = wbi + rout <= vbr;
            if (uin & !win) {
                return toChars(sbi,  e);
            }
            if (!uin & win) {
                return toChars(sbi + di, e);
            }
            if (uin) {
                int cmp = (int) (2 * vb - ubi - wbi);
                if (cmp < 0 || cmp == 0 && (sbi / di & 0x1) == 0) {
                    return toChars(sbi, e);
                }
                return toChars(sbi + di,  e);
            }
        }
        throw new AssertionError("unreachable code");
    }

    private String fullCaseXL(int qb, long cb, long cb_r) {
        int p = H - e + qb;
        Natural vb = valueOfShiftLeft(cb, p);
        Natural vbl = valueOfShiftLeft(cb - 1, p);
        Natural vbr = valueOfShiftLeft(cb_r, p);
        Natural m = pow5(e - H);
        long sbH = vb.divide(m);
        for (int g = H - G; g >= 0; --g) {
            long di = pow10(g);
            long sbi = sbH - sbH % di;
            Natural ubi = m.multiply(sbi);
            Natural wbi = ubi.addShiftLeft(pow5(e - H + g), g);
            boolean uin = vbl.compareTo(ubi) + lout <= 0;
            boolean win = wbi.compareTo(vbr) + rout <= 0;
            if (uin & !win) {
                return toChars(sbi,  e);
            }
            if (!uin & win) {
                return toChars(sbi + di, e);
            }
            if (uin) {
                int cmp = vb.closerTo(ubi, wbi);
                if (cmp < 0 || cmp == 0 && (sbi / di & 0x1) == 0) {
                    return toChars(sbi, e);
                }
                return toChars(sbi + di,  e);
            }
        }
        throw new AssertionError("unreachable code");
    }

    /*
    A faster version that succeeds in about 99.5% of the cases.
    It must be invoked only on values greater than MIN_NORMAL.
    When it fails, it resorts to the full() version.
     */
    private String reduced() {
        int p = -P - q - pow10r(H - e);
        long t = floorPow10d(H - e);
        long cb = c << D;
        long vh = multiplyHighUnsigned(cb, t);
        long cbl = cb - (1L << D - (c != Double.C_MIN ? 1 : 2));
        long vhl = multiplyHighUnsigned(cbl, t);
        long cbr = cb + (1L << D - 1);
        long vhr = multiplyHighUnsigned(cbr, t);
        long shH = vh >>> p;
        long vhu = vh + 2;
        for (int g = H - G; g >= 0; --g) {
            long di = pow10(g);
            long uhi = shH - shH % di << p;
            long whi = uhi + (di << p);
            boolean uin = uhi - vhl >= 2;
            boolean wout = whi - vhr >= 2;
            if (uin & wout) {
                return toChars(uhi >>> p, e);
            }
            boolean uout = uhi - vhl - lout < 0;
            boolean win = whi - vhr + rout <= 0;
            if (uout & win) {
                return toChars(whi >>> p, e);
            }
            if (uin & win) {
                if (vhu - uhi <= whi - vhu) {
                    return toChars(uhi >>> p, e);
                }
                if (whi - vh < vh - uhi) {
                    return toChars(whi >>> p, e);
                }
                return full();
            }
            if (!uout & !uin | !wout) {
                return full();
            }
        }
        throw new AssertionError("unreachable code");
    }

    /*
    Limited usage, but does magic during JIT compilation. Note that
    0 <= g <= 2 = H - G when invoked, so the default branch is never taken.
     */
    private long pow10(int g) {
        switch (g) {
            case 0:
                return 1;
            case 1:
                return 10;
            case 2:
                return 100;
            default:
                return 0;
        }
    }

    /*
    f comes from integer(), from full() or from reduced().
    In the former case
        10^8 <= f < 10^9
    and the method formats the number (f * 10^8) * 10^(e-H).
    Otherwise
        10^(H-1) <= f <= 10^H
    and the method formats the number f * 10^(e-H)

    Division is avoided, where possible, by replacing it with
multiplications
    and shifts. This makes a noticeable difference in performance, in
    particular when generating the digits of the exponent.
    For more in-depth readings, see for example
    Moeller N, Granlund T, "Improved division by invariant integers"
    ridiculous_fish, "Labor of Division (Episode III): Faster Unsigned
        Division by Constants"

    Also, once the quotient is known, the remainder is computed indirectly.
     */
    private String toChars(long f, int e) {
        int h; // the 1 most significant
        int m; // the next 8 most significant digits
        int l; // the 8 least significant digits
        if (f != MAX_SIGNIFICAND) {
            long hm;
            if (f < 1_000_000_000L) {
                hm = f;
                l = 0;
            } else {
                hm = f / 100_000_000L;
                l = (int) (f - 100_000_000L * hm);
            }
            h = (int) (hm * 1_441_151_881L >>> 57); // h = hm / 100_000_000
            m = (int) (hm - 100_000_000 * h);
        } else {
            // This might happen for doubles close or equal to powers of 10
            h = 1;
            m = l = 0;
            e += 1;
        }
        /*
        The left-to-right digits generation in toChars_* is inspired by
        Bouvier C, Zimmermann P, "Division-Free Binary-to-Decimal
Conversion"
         */
        if (0 < e && e <= 7) {
            return toChars_1(h, m, l, e);
        }
        if (-3 < e && e <= 0) {
            return toChars_2(h, m, l, e);
        }
        return toChars_3(h, m, l, e);
    }

    private String toChars_1(int h, int m, int l, int e) {
        // 0 < e <= 7
        appendDigit(h);
        int y = (int) (((long) (m + 1) << LTR) / 100_000_000L) - 1;
        int t;
        int i = 1;
        for (; i < e; ++i) {
            t = 10 * y;
            appendDigit(t >>> LTR);
            y = t & MASK_LTR;
        }
        append('.');
        for (; i <= 8; ++i) {
            t = 10 * y;
            appendDigit(t >>> LTR);
            y = t & MASK_LTR;
        }
        lowDigits(l);
        return charsToString();
    }

    private String toChars_2(int h, int m, int l, int e) {
      // -3 < e <= 0
      appendDigit(0);
      append('.');
      for (; e < 0; ++e) {
          appendDigit(0);
      }
      appendDigit(h);
      append8Digits(m);
      lowDigits(l);
      return charsToString();
    }

    private String toChars_3(int h, int m, int l, int e) {
        // computerized scientific notation
        appendDigit(h);
        append('.');
        append8Digits(m);
        lowDigits(l);
        exponent(e - 1);
        return charsToString();
    }

    private void lowDigits(int l) {
        if (l != 0) {
            append8Digits(l);
        }
        removeTrailingZeroes();
    }

    private void append8Digits(int v) {
        int y = (int) (((long) (v + 1) << LTR) / 100_000_000L) - 1;
        for (int i = 0; i < 8; ++i) {
            int t = 10 * y;
            appendDigit(t >>> LTR);
            y = t & MASK_LTR;
        }
    }

    private void removeTrailingZeroes() {
        while (buf[index] == '0') {
            --index;
        }
        if (buf[index] == '.') {
            ++index;
        }
    }

    private void exponent(int e) {
        append('E');
        if (e < 0) {
            append('-');
            e = -e;
        }
        if (e < 10) {
            appendDigit(e);
        } else if (e < 100) {
            int d = e * 205 >>> 11; // d = e / 10
            appendDigit(d);
            appendDigit(e - 10 * d);
        } else {
            int d = e * 1_311 >>> 17; // d = e / 100
            appendDigit(d);
            e -= 100 * d;
            d = e * 205 >>> 11; // d = e / 10
            appendDigit(d);
            appendDigit(e - 10 * d);
        }
    }

    private void append(int c) {
        buf[++index] = (char) c;
    }

    private void appendDigit(int d) {
        buf[++index] = (char) ('0' + d);
    }

    private String charsToString() {
        return new String(buf, 0, index + 1);
    }

}

-------- math.DecimalChecker.java

/*
 * Copyright (c) 2018, Raffaello Giulietti. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 * This particular file is subject to the "Classpath" exception as provided
 * in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 */

package math;

import java.io.IOException;
import java.io.StringReader;
import java.math.BigDecimal;

class DecimalChecker {

    /*
    Returns whether s syntactically meets the expected output of
    Double.toString(double). It is restricted to finite positive outputs.
    It is an unusually long method but rather straightforward, too.
    Many conditionals could be merged, but KISS here.
     */
    private static boolean hasCorrectFormat(String s) {
        try {
            // first determine interesting boundaries in the string
            StringReader r = new StringReader(s);
            int c = r.read();

            int i = 0;
            while (c == '0') {
                ++i;
                c = r.read();
            }
            // i is just after zeroes starting the integer

            int d = i;
            while ('0' <= c && c <= '9') {
                ++d;
                c = r.read();
            }
            // d is just after digits ending the integer

            int fz = d;
            if (c == '.') {
                ++fz;
                c = r.read();
            }
            // fz is just after a decimal '.'

            int f = fz;
            while (c == '0') {
                ++f;
                c = r.read();
            }
            // f is just after zeroes starting the fraction

            int x = f;
            while ('0' <= c && c <= '9') {
                ++x;
                c = r.read();
            }
            // x is just after digits ending the fraction

            int g = x;
            if (c == 'E') {
                ++g;
                c = r.read();
            }
            // g is just after an exponent indicator 'E'

            int ez = g;
            if (c == '-') {
                ++ez;
                c = r.read();
            }
            // ez is just after a '-' sign in the exponent

            int e = ez;
            while (c == '0') {
                ++e;
                c = r.read();
            }
            // e is just after zeroes starting the exponent

            int z = e;
            while ('0' <= c && c <= '9') {
                ++z;
                c = r.read();
            }
            // z is just after digits ending the exponent

            // No other chars after the number
            if (z != s.length()) {
                return false;
            }

            // The integer must be present
            if (d == 0) {
                return false;
            }

            // The decimal '.' must be present
            if (fz == d) {
                return false;
            }

            // The fraction must be present
            if (x == fz) {
                return false;
            }

            // Plain notation, no exponent
            if (x == z) {
                // At most one 0 starting the integer
                if (i > 1) {
                    return false;
                }

                // The integer cannot have more than 7 digits
                if (d > 7) {
                    return false;
                }

                // If the integer is 0, at most 2 zeroes start the fraction
                if (i == 1 && f - fz > 2) {
                    return false;
                }

                // OK for plain notation
                return true;
            }

            // Computerized scientific notation

            // The integer has exactly one nonzero digit
            if (i != 0 || d != 1) {
                return false;
            }

            // There must be an exponent indicator
            if (x == g) {
                return false;
            }

            // There must be an exponent
            if (ez == z) {
                return false;
            }

            // The exponent must not start with zeroes
            if (ez != e) {
                return false;
            }

            int exp;
            // The exponent must parse as an int
            try {
                exp = Integer.parseInt(s, g, z, 10);
            } catch (NumberFormatException ex) {
                return false;
            }

            // The exponent must not lie in [-3, 7)
            if (-3 <= exp && exp < 7) {
                return false;
            }

            // OK for computerized scientific notation
            return true;
        } catch (IOException ex) {
            // An IOException on a StringReader??? Please...
            return false;
        }
    }

    /*
    And KISS even here.
     */
    static boolean isCorrect(double v, String s) {
        if (v != v) {
            return s.equals("NaN");
        }
        if (Double.doubleToRawLongBits(v) < 0) {
            if (s.isEmpty() || s.charAt(0) != '-') {
                return false;
            }
            return isCorrect(-v, s.substring(1));
        }
        if (v == Double.POSITIVE_INFINITY) {
            return s.equals("Infinity");
        }
        if (v == 0) {
            return s.equals("0.0");
        }
        if (!hasCorrectFormat(s)) {
            return false;
        }
        // s must of course recover v
        try {
            if (v != Double.parseDouble(s)) {
                return false;
            }
        } catch (NumberFormatException e) {
            return false;
        }

        // b = d * 10^r for some integers d, r with d > 0
        BigDecimal b = new BigDecimal(s);

        // d > 0 has at most 17 digits, so must fit in a positive long
        if (b.unscaledValue().bitLength() >= Long.SIZE) {
            return false;
        }
        long d = b.unscaledValue().longValue();
        if (d >= 100_000_000_000_000_000L) {
            return false;
        }
        int r = -b.scale();

        // Determine the number of digits in d
        int len2 = Long.SIZE - Long.numberOfLeadingZeros(d);
        int len10 = MathUtils.ord10pow2(len2) - 1;
        if (d >= Powers.pow10[len10]) {
            len10 += 1;
        }

        // ord10 is such that 10^(ord10-1) <= v < 10^ord10
        int ord10 = r + len10;

        // Plain format iff -3 < ord10 <= 7
        boolean isPlain = -3 < ord10 && ord10 <= 7;

        // If plain then len10 > ord10, i.e., r < 0
        if (isPlain && r >= 0) {
            return false;
        }

        // If plain, trailing zero in fraction only if r = -1
        if (isPlain && d % 10 == 0 && r < -1) {
            return false;
        }

        // If not plain, trailing zero in fraction only if len10 = 2
        if (!isPlain && d % 10 == 0 && len10 > 2) {
            return false;
        }

        // Get rid of trailing zeroes
        while (d % 10 == 0) {
            d /= 10;
            r += 1;
            len10 -= 1;
        }

        if (len10 > 1) {
            // Try with a shorter number less than v
            long dsd = d / 10;
            int rsd = r + 1;
            BigDecimal bsd = BigDecimal.valueOf(dsd, -rsd);
            if (dsd >= 10 && bsd.doubleValue() == v) {
                return false;
            }

            // ... and with a shorter number greater than v
            long dsu = d / 10 + 1;
            int rsu = r + 1;
            BigDecimal bsu = BigDecimal.valueOf(dsu, -rsu);
            if (dsu > 10 && bsu.doubleValue() == v) {
                return false;
            }
        }

        BigDecimal bv = new BigDecimal(v);
        BigDecimal deltav = b.subtract(bv).abs();

        // Check if the decimal predecessor is closer
        long dsp = d - 1;
        BigDecimal bsp = BigDecimal.valueOf(dsp, -r);
        int cmpp = 1;
        if (bsp.doubleValue() == v) {
            BigDecimal deltap = bsp.subtract(bv).abs();
            cmpp = deltap.compareTo(deltav);
            if (cmpp < 0) {
                return false;
            }
        }

        // Check if the decimal successor is closer
        long dss = d + 1;
        BigDecimal bss = BigDecimal.valueOf(dss, -r);
        int cmps = 1;
        if (bss.doubleValue() == v) {
            BigDecimal deltas = bss.subtract(bv).abs();
            cmps = deltas.compareTo(deltav);
            if (cmps < 0) {
                return false;
            }
        }

        if (cmpp == 0 && (d & 0x1) != 0) {
            return false;
        }

        if (cmps == 0 && (d & 0x1) != 0) {
            return false;
        }

        return true;
    }

}

-------- math.DoubleToDecimalTest.java

/*
 * Copyright (c) 2018, Raffaello Giulietti. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 * This particular file is subject to the "Classpath" exception as provided
 * in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 */

package math;

import org.junit.Test;

import java.util.Random;

import static java.lang.Math.scalb;
import static junit.framework.TestCase.*;
import static math.DecimalChecker.isCorrect;
import static math.DoubleToDecimal.Double.E_MAX_VALUE;
import static math.DoubleToDecimal.Double.E_MIN_VALUE;

public class DoubleToDecimalTest {

    private String toDecimal(double v) {
        String s = DoubleToDecimal.toString(v);
        assertTrue(isCorrect(v, s));
        return s;
    }

    @Test
    public void testExtremeValues() {
        toDecimal(Double.NEGATIVE_INFINITY);
        toDecimal(-Double.MAX_VALUE);
        toDecimal(-Double.MIN_NORMAL);
        toDecimal(-Double.MIN_VALUE);
        toDecimal(-0.0);
        toDecimal(0.0);
        toDecimal(Double.MIN_VALUE);
        toDecimal(Double.MIN_NORMAL);
        toDecimal(Double.MAX_VALUE);
        toDecimal(Double.POSITIVE_INFINITY);
        toDecimal(Double.NaN);
    }

    /*
    A few powers of 10 are incorrectly rendered by the JDK.
    The rendering is either too long or it is not the closest decimal.
     */
    @Test
    public void testPowersOf10() {
        for (int e = E_MIN_VALUE; e <= E_MAX_VALUE; ++e) {
            toDecimal(Double.parseDouble("1e" + e));
        }
    }

    /*
    Many powers of 2 are incorrectly rendered by the JDK.
    The rendering is either too long or it is not the closest decimal.
     */
    @Test
    public void testPowersOf2() {
        for (double v = Double.MIN_VALUE; v <= Double.MAX_VALUE; v *= 2.0) {
            toDecimal(v);
        }
    }

    /*
    There are tons of doubles that are rendered incorrectly by the JDK.
    While the renderings correctly round back to the original value,
    they are longer than needed or are not the closest decimal to the
double.
    Here are just a very few examples.
     */
    private static final String[] Anomalies = {
            // JDK renders these, and others, with 18 digits!
            "2.82879384806159E17", "1.387364135037754E18",
            "1.45800632428665E17",

            // JDK renders these longer than needed.
            "1.6E-322", "6.3E-322",
            "7.3879E20", "2.0E23", "7.0E22", "9.2E22",
            "9.5E21", "3.1E22", "5.63E21", "8.41E21",

            // JDK does not render these, and many others, as the closest.
            "9.9E-324", "9.9E-323",
            "1.9400994884341945E25", "3.6131332396758635E25",
            "2.5138990223946153E25",
    };

    @Test
    public void testSomeAnomalies() {
        for (String dec : Anomalies) {
            toDecimal(Double.parseDouble(dec));
        }
    }

    /*
    Values are from
    Paxson V, "A Program for Testing IEEE Decimal–Binary Conversion"
     */
    private static final double[] PaxsonSignificands = {
            8_511_030_020_275_656L,
            5_201_988_407_066_741L,
            6_406_892_948_269_899L,
            8_431_154_198_732_492L,
            6_475_049_196_144_587L,
            8_274_307_542_972_842L,
            5_381_065_484_265_332L,
            6_761_728_585_499_734L,
            7_976_538_478_610_756L,
            5_982_403_858_958_067L,
            5_536_995_190_630_837L,
            7_225_450_889_282_194L,
            7_225_450_889_282_194L,
            8_703_372_741_147_379L,
            8_944_262_675_275_217L,
            7_459_803_696_087_692L,
            6_080_469_016_670_379L,
            8_385_515_147_034_757L,
            7_514_216_811_389_786L,
            8_397_297_803_260_511L,
            6_733_459_239_310_543L,
            8_091_450_587_292_794L,

            6_567_258_882_077_402L,
            6_712_731_423_444_934L,
            6_712_731_423_444_934L,
            5_298_405_411_573_037L,
            5_137_311_167_659_507L,
            6_722_280_709_661_868L,
            5_344_436_398_034_927L,
            8_369_123_604_277_281L,
            8_995_822_108_487_663L,
            8_942_832_835_564_782L,
            8_942_832_835_564_782L,
            8_942_832_835_564_782L,
            6_965_949_469_487_146L,
            6_965_949_469_487_146L,
            6_965_949_469_487_146L,
            7_487_252_720_986_826L,
            5_592_117_679_628_511L,
            8_887_055_249_355_788L,
            6_994_187_472_632_449L,
            8_797_576_579_012_143L,
            7_363_326_733_505_337L,
            8_549_497_411_294_502L,
    };

    private static final int[] PaxsonExponents = {
            -342,
            -824,
            237,
            72,
            99,
            726,
            -456,
            -57,
            376,
            377,
            93,
            710,
            709,
            117,
            -1,
            -707,
            -381,
            721,
            -828,
            -345,
            202,
            -473,

            952,
            535,
            534,
            -957,
            -144,
            363,
            -169,
            -853,
            -780,
            -383,
            -384,
            -385,
            -249,
            -250,
            -251,
            548,
            164,
            665,
            690,
            588,
            272,
            -448,
    };

    @Test
    public void testPaxson() {
        for (int i = 0; i < PaxsonSignificands.length; ++i) {
            toDecimal(scalb(PaxsonSignificands[i], PaxsonExponents[i]));
        }
    }

    /*
    Tests all integers of the form yx_xxx_000_000_000_000_000, y != 0.
    These are all exact doubles.
     */
    @Test
    public void testLongs() {
        for (int i = 10_000; i < 100_000; ++i) {
            String s = toDecimal(i * 1e15);
            String xp = Integer.toString(i);
            int j = 5;
            while (--j >= 2 && xp.charAt(j) == '0') ; // empty body intended
            xp = xp.substring(0, 1) + "." + xp.substring(1, j + 1) + "E19";
            assertEquals(xp, s);
        }
    }

    /*
    Tests all integers up to 100_000.
    These are all exact doubles.
     */
    @Test
    public void testInts() {
        for (int i = -100_000; i <= 100_000; ++i) {
            String s = toDecimal(i);
            String xp = Integer.toString(i) + ".0";
            assertEquals(xp, s);
        }
    }

    /*
    Random doubles over the whole range
     */
    @Test
    public void testRandom() {
        Random r = new Random();
        for (int i = 0; i < 10_000; ++i) {
            toDecimal(Double.longBitsToDouble(r.nextLong()));
        }
    }

    /*
    Random doubles over the integer range [0, 10^15).
    These integers are all exact doubles.
     */
    @Test
    public void testRandomUnit() {
        Random r = new Random();
        for (int i = 0; i < 10_000; ++i) {
            toDecimal(r.nextLong() % 1_000_000_000_000_000L);
        }
    }

    /*
    Random doubles over the range [0, 10^15) as "multiples" of 1e-3
     */
    @Test
    public void testRandomMilli() {
        Random r = new Random();
        for (int i = 0; i < 10_000; ++i) {
            toDecimal(r.nextLong() % 1_000_000_000_000_000_000L / 1e3);
        }
    }

    /*
    Random doubles over the range [0, 10^15) as "multiples" of 1e-6
     */
    @Test
    public void testRandomMicro() {
        Random r = new Random();
        for (int i = 0; i < 10_000; ++i) {
            toDecimal(r.nextLong() / 1e6);
        }
    }

}

-------- math.D2DBenchmark.java

/*
 * Copyright (c) 2018, Raffaello Giulietti. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 * This particular file is subject to the "Classpath" exception as provided
 * in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 */

package math;

import java.text.DecimalFormat;
import java.util.Random;

/*
Some simple benchmarks to evaluate speeds.
 */
public class D2DBenchmark {

    private static final int N = 100_000_000;
    private static final double[] x = new double[N];
    private static final DecimalFormat intFormat =
            new DecimalFormat("#,##0");
    private static final DecimalFormat doubleFormat =
            new DecimalFormat("#,##0.000");
    private static final int RUNS_PER_LIB = 3;
    private static Random r;
    private static long d2dNs;
    private static long jdkNs;

    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("arguments");
            System.out.println("  [ <seed> ]");
            System.out.println();
        }
        Long seed = args.length > 0 ? Long.parseLong(args[0]) : null;
        r = seed != null ? new Random(seed) : new Random();
        micro();
        milli();
        integers();
        nonNaNRange();
    }

    private static void benchmark() {
        d2dNs = jdkNs = 0;
        for (int i = 1; i <= RUNS_PER_LIB; ++i) {
            benchmarkD2d(i);
        }
        for (int i = 1; i <= RUNS_PER_LIB; ++i) {
            benchmarkJdk(i);
        }
        printSpeedup();
    }

    private static void micro() {
        prepareMicro();
        benchmark();
    }

    private static void milli() {
        prepareMilli();
        benchmark();
    }

    private static void integers() {
        prepareIntegers();
        benchmark();
    }

    private static void nonNaNRange() {
        prepareNonNaNDoubles();
        benchmark();
    }

    private static void prepareIntegers() {
        System.out.print("generating " + intFormat.format(x.length)
                + " integer random doubles... ");
        System.out.flush();
        for (int i = 0; i < x.length; ++i) {
            x[i] = r.nextInt();
        }
        System.out.println("finished");
    }

    private static void prepareMilli() {
        System.out.print("generating " + intFormat.format(x.length)
                + " \"milli\" random doubles... ");
        System.out.flush();
        for (int i = 0; i < x.length; ++i) {
            x[i] = r.nextInt() / 1e3;
        }
        System.out.println("finished");
    }

    private static void prepareMicro() {
        System.out.print("generating " + intFormat.format(x.length)
                + " \"micro\" random doubles... ");
        System.out.flush();
        for (int i = 0; i < x.length; ++i) {
            x[i] = r.nextInt() / 1e6;
        }
        System.out.println("finished");
    }

    private static void prepareNonNaNDoubles() {
        System.out.print("generating " + intFormat.format(x.length)
                + " non NaN random doubles... ");
        System.out.flush();
        int i = 0;
        while (i < x.length) {
            double v = Double.longBitsToDouble(r.nextLong());
            if (v == v) {
                x[i++] = v;
            }
        }
        System.out.println("finished");
    }

    private static void benchmarkJdk(int take) {
        long tot = 0;
        long begin = System.nanoTime();
        for (double v : x) {
            tot += Double.toString(v).length();
        }
        long ns = System.nanoTime() - begin;
        jdkNs += ns;
        print("java.lang.Double",take, ns, tot);
    }

    private static void benchmarkD2d(int take) {
        long tot = 0;
        long begin = System.nanoTime();
        for (double v : x) {
            tot += DoubleToDecimal.toString(v).length();
        }
        long ns = System.nanoTime() - begin;
        d2dNs += ns;
        print("math.DoubleToDecimal", take, ns, tot);
    }

    private static void print(String lib, int take, long ns, long tot) {
        System.out.println(lib + "[" + take + "/" + RUNS_PER_LIB + "]");
        System.out.println("--------");
        System.out.println("n=" + intFormat.format(x.length));
        System.out.println("elapsed=" + intFormat.format(ns) + " ns");
        System.out.println(intFormat.format(ns / x.length) + "
ns/rendering");
        System.out.println("total length of output=" +
intFormat.format(tot));
        System.out.println();
    }

    private static void printSpeedup() {
        System.out.println("speedup factor=" +
                doubleFormat.format((double) jdkNs / (double) d2dNs));
        System.out.println();
    }

}



More information about the core-libs-dev mailing list