001/*
002 * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
003 * Copyright (C) 2006 - JScience (http://jscience.org/)
004 * All rights reserved.
005 * 
006 * Permission to use, copy, modify, and distribute this software is
007 * freely granted, provided that this notice is preserved.
008 */
009package org.jscience.mathematics.number;
010
011import org.jscience.mathematics.structure.Field;
012
013import javolution.lang.MathLib;
014import javolution.context.HeapContext;
015import javolution.context.LocalContext;
016import javolution.context.ObjectFactory;
017import javolution.text.Text;
018import javolution.text.TypeFormat;
019import javolution.xml.XMLFormat;
020import javolution.xml.stream.XMLStreamException;
021
022/**
023 * <p> This class represents a real number of arbitrary precision with 
024 *     known/guaranteed uncertainty. A real number consists of a 
025 *     {@link #getSignificand significand}, a maximum {@link #getError error} 
026 *     (on the significand value) and a decimal {@link #getExponent exponent}: 
027 *     (<code>(significand ± error) · 10<sup>exponent</sup></code>).</p>
028 *     
029 * <p> Reals number can be {@link #isExact exact} (e.g. integer values 
030 *     scaled by a power of ten). Exactness is maintained for
031 *     {@link org.jscience.mathematics.structure.Ring Ring} operations
032 *     (e.g. addition, multiplication), but typically lost when a 
033 *     multiplicative {@link #inverse() inverse} is calculated. The minimum 
034 *     precision used for exact numbers is set by 
035 *     {@link #setExactPrecision(int)} ({@link 
036 *     javolution.context.LocalContext context local} setting, default
037 *     <code>19</code> digits).<p>
038 * 
039 * <p> The actual {@link #getPrecision precision} and {@link #getAccuracy 
040 *     accuracy} of any real number is available and <b>guaranteed</b> 
041 *     (the true/exact value is always within the precision/accuracy range).</p>
042 * 
043 * <p> Operations on instances of this class are quite fast   
044 *     as information substantially below the precision level (aka noise)
045 *     is not processed/stored. There is no limit on a real precision
046 *     but precision degenerates (due to numeric errors) and calculations 
047 *     accelerate as more and more operations are performed.</p>
048 * 
049 * <p> Instances of this class can be utilized to find approximate 
050 *     solutions to linear equations using the 
051 *     {@link org.jscience.mathematics.vector.Matrix Matrix} class for which
052 *     high-precision reals is often required, the primitive type
053 *     <code>double</code> being not accurate enough to resolve equations 
054 *     when the matrix's size exceeds 100x100. Furthermore, even for small 
055 *     matrices the "qualified" result is indicative of possible system 
056 *     singularities.</p>
057 *  
058 * @author <a href="mailto:jean-marie@dautelle.com">Jean-Marie Dautelle</a>
059 * @version 3.3, January 8, 2006
060 * @see <a href="http://en.wikipedia.org/wiki/Real_number">
061 *      Wikipedia: Real number</a>
062 */
063public final class Real extends Number<Real> implements Field<Real> {
064
065    /**
066     * Holds the default XML representation for real numbers.
067     * This representation consists of a simple <code>value</code> attribute
068     * holding the {@link #toText() textual} representation.
069     */
070    static final XMLFormat<Real> XML = new XMLFormat<Real>(Real.class) {
071
072        @Override
073        public Real newInstance(Class<Real> cls, InputElement xml)
074                throws XMLStreamException {
075            return Real.valueOf(xml.getAttribute("value"));
076        }
077
078        public void write(Real real, OutputElement xml)
079                throws XMLStreamException {
080            xml.setAttribute("value", real.toText());
081        }
082
083        public void read(InputElement xml, Real real) {
084            // Nothing to do, immutable.
085        }
086    };
087
088    /** 
089     * Holds a Not-a-Number instance (infinite error). 
090     */
091    public static final Real NaN = new Real(); // Unique (0 ± 1E2147483647)
092    static {
093        NaN._significand = LargeInteger.ZERO;
094        NaN._error = LargeInteger.ONE;
095        NaN._exponent = Integer.MAX_VALUE;
096    }
097
098    /** 
099     * Holds the exact ZERO instance. 
100     */
101    public static final Real ZERO;
102
103    /** 
104     * Holds the exact ONE instance. 
105     */
106    public static final Real ONE;
107
108    /**
109     * Holds local precision for exact number.
110     */
111    private static final LocalContext.Reference<Integer> EXACT_PRECISION = new LocalContext.Reference<Integer>(
112            new Integer(19));
113
114    /**
115     * The significand value.
116     */
117    private LargeInteger _significand;
118
119    /**
120     * The significand error (0 for exact number).
121     */
122    private LargeInteger _error;
123
124    /**
125     * The decimal exponent.
126     */
127    private int _exponent;
128
129    /**
130     * Default constructor.
131     */
132    private Real() {
133    }
134
135    /**
136     * Returns the {@link javolution.context.LocalContext local} minimum 
137     * precision (number of exact digits) when exact numbers have to be
138     * approximated.
139     * 
140     * @return the minimum number of digits assumed exact for {@link #isExact 
141     *         exact} real numbers.
142     */
143    public static int getExactPrecision() {
144        return EXACT_PRECISION.get();
145    }
146
147    /**
148     * Sets the {@link javolution.context.LocalContext local} minimum precision
149     * (number of exact digits) when exact numbers have to be approximated.
150     * 
151     * @param precision the minimum number of digits assumed exact for 
152     *        {@link #isExact exact} numbers.
153     */
154    public static void setExactPrecision(int precision) {
155        EXACT_PRECISION.set(precision);
156    }
157
158    /**
159     * Returns a real having the specified significand, error and exponent values.
160     * If the error is <code>0</code>, the real is assumed exact. 
161     * For example:[code]
162     * 
163     *     // x = 0.0 ± 0.01 
164     *     Real x = Real.valueOf(LargeInteger.ZERO, 1, -2);
165     *                           
166     *      // y = -12.3 exact 
167     *     Real y = Real.valueOf(LargeInteger.valueOf(-123), 0, -1);
168     * 
169     * [/code]
170     * 
171     * @param significand this real significand.
172     * @param error the maximum error on the significand.
173     * @param exponent the decimal exponent.
174     * @return <code>(significand ± error)·10<sup>exponent</sup>)</code>
175     * @throws IllegalArgumentException if <code>error < 0</code>
176     */
177    public static Real valueOf(LargeInteger significand, int error,
178            int exponent) {
179        if (error < 0)
180            throw new IllegalArgumentException("Error cannot be negative");
181        Real real = FACTORY.object();
182        real._significand = significand;
183        real._error = LargeInteger.valueOf(error);
184        real._exponent = exponent;
185        return real;
186    }
187
188    /**
189     * Returns the real number (inexact except for <code>0.0</code>) 
190     * corresponding to the specified <code>double</code> value. 
191     * The error is derived from the inexact representation of 
192     * <code>double</code> values intrinsic to the 64 bits IEEE 754 format.
193     * 
194     * @param doubleValue the <code>double</code> value to convert.
195     * @return the corresponding real number.
196     */
197    public static Real valueOf(double doubleValue) {
198        if (doubleValue == 0.0)
199            return Real.ZERO;
200        if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue))
201            return Real.NaN;
202        // Find the exponent e such as: value == x.xxx * 10^e
203        int e = MathLib.floorLog10(doubleValue) - 18 + 1; // 18 digits significand.
204        long significand = MathLib.toLongPow10(doubleValue, -e);
205        int error = (int) MathLib.toLongPow10(Math.ulp(doubleValue), -e) + 1;
206        return Real.valueOf(LargeInteger.valueOf(significand), error, e);
207    }
208
209    /**
210     * Returns the exact real number corresponding to the specified 
211     * <code>long</code> value (convenience method).  
212     * 
213     * @param longValue the exact long value.
214     * @return <code>Real.valueOf(LargeInteger.valueOf(longValue), 0, 0)</code>
215     */
216    public static Real valueOf(long longValue) {
217        return Real.valueOf(LargeInteger.valueOf(longValue), 0, 0);
218    }
219
220    /**
221     * Returns the real for the specified character sequence.
222     * If the precision is not specified (using the <code>±</code> symbol), 
223     * the real is supposed exact. Example of valid character sequences:
224     * <li>"1.2E3" (1200 exact)</li>
225     * <li>"1.2E3±1E-2" (1200 ± 0.01)</li></ul>
226     * 
227     * @param  chars the character sequence.
228     * @return the corresponding real number.
229     * @throws NumberFormatException if the character sequence does not contain
230     *         a parsable real.
231     */
232    public static Real valueOf(CharSequence chars) throws NumberFormatException {
233        Text txt = Text.valueOf(chars); // TODO Use TextFormat...
234        if ((txt.length() == 3) && (txt.indexOf("NaN", 0) == 0))
235            return NaN;
236        if (txt.equals("0"))
237            return ZERO;
238        int exponentIndex = txt.indexOf("E", 0);
239        if (exponentIndex >= 0) {
240            int exponent = TypeFormat.parseInt(txt.subtext(exponentIndex + 1,
241                    txt.length()));
242            Real r = valueOf(txt.subtext(0, exponentIndex));
243            if (r == ZERO)
244                return valueOf(LargeInteger.ZERO, 1, exponent);
245            r._exponent += exponent;
246            return r;
247        }
248        Real real = FACTORY.object();
249        int errorIndex = txt.indexOf("±", 0);
250        if (errorIndex >= 0) {
251            real._significand = LargeInteger.valueOf(txt.subtext(0, errorIndex));
252            real._error = LargeInteger.valueOf(txt.subtext(errorIndex + 1, txt
253                    .length()));
254            if (real._error.isNegative())
255                throw new NumberFormatException(chars
256                        + " not parsable (error cannot be negative)");
257            real._exponent = 0;
258            return real;
259        }
260        int decimalPointIndex = txt.indexOf(".", 0);
261        if (decimalPointIndex >= 0) {
262            LargeInteger integer = LargeInteger.valueOf(txt.subtext(0,
263                    decimalPointIndex));
264            LargeInteger fraction = LargeInteger.valueOf(txt.subtext(
265                    decimalPointIndex + 1, txt.length()));
266            int fractionDigits = chars.length() - decimalPointIndex - 1;
267            real._significand = integer.isNegative() ? integer.times10pow(
268                    fractionDigits).minus(fraction) : integer.times10pow(
269                    fractionDigits).plus(fraction);
270            real._error = LargeInteger.ZERO;
271            real._exponent = -fractionDigits;
272            return real;
273        } else {
274            real._significand = LargeInteger.valueOf(chars);
275            real._error = LargeInteger.ZERO;
276            real._exponent = 0;
277            return real;
278        }
279    }
280
281    /**
282     * Returns this real <a href="http://en.wikipedia.org/wiki/Significand">
283     * significand</a> value.
284     * 
285     * @return the significand.
286     */
287    public LargeInteger getSignificand() {
288        return _significand;
289    }
290
291    /**
292     * Returns the maximum error (positive) on this real significand.
293     * 
294     * @return the maximum error on the significand.
295     */
296    public int getError() {
297        return _error.intValue();
298    }
299
300    /**
301     * Returns the exponent of the power of 10 multiplier.
302     * 
303     * @return the decimal exponent.
304     */
305    public int getExponent() {
306        return _exponent;
307    }
308
309    /**
310     * Indicates if this real number is exact (<code>{@link #getError() error} 
311     * == 0</code>).
312     *
313     * @return <code>getError() == 0</code>
314     */
315    public boolean isExact() {
316        return _error.isZero();
317    }
318
319    /**
320     * Returns the number of decimal digits guaranteed exact which appear to
321     * the right of the decimal point (absolute error).
322     *
323     * @return a measure of the absolute error of this real number.
324     */
325    public int getAccuracy() {
326        if (_error.isZero())
327            return Integer.MAX_VALUE;
328        if (this == NaN)
329            return Integer.MIN_VALUE;
330        return -_exponent - _error.digitLength();
331    }
332
333    /**
334     * Returns the total number of decimal digits guaranteed exact
335     * (relative error).
336     *
337     * @return a measure of the relative error of this real number.
338     */
339    public final int getPrecision() {
340        if (_error.isZero())
341            return Integer.MAX_VALUE;
342        if (this == NaN)
343            return Integer.MIN_VALUE;
344        return _significand.digitLength() - _error.digitLength();
345    }
346
347    /**
348     * Indicates if this real is greater than zero.
349     * 
350     * @return <code>this > 0</code>
351     */
352    public boolean isPositive() {
353        return _significand.isPositive();
354    }
355
356    /**
357     * Indicates if this real is less than zero.
358     * 
359     * @return <code>this < 0</code>
360     */
361    public boolean isNegative() {
362        return _significand.isNegative();
363    }
364
365    /**
366     * Indicates if this real is Not-a-Number (unbounded value interval).
367     * 
368     * @return <code>true</code> if this number has unbounded value interval;
369     *         <code>false</code> otherwise.
370     */
371    public boolean isNaN() {
372        return this == NaN;
373    }
374
375    /**
376     * Indicates if this real approximates the one specified. 
377     * This method takes into account possible errors (e.g. numeric
378     * errors) to make this determination.
379     *  
380     * <p>Note: This method returns <code>true</code> if <code>this</code> or 
381     *          <code>that</code> {@link #isNaN} (basically Not-A-Number 
382     *          approximates anything).</p>
383     *
384     * @param  that the real to compare with.
385     * @return <code>this &asymp; that</code>
386     */
387    public boolean approximates(Real that) {
388        Real diff = this.minus(that);
389        if (diff == NaN)
390            return false;
391        return diff._error.isLargerThan(diff._significand);
392    }
393
394    /**
395     * Returns the closest integer value to this rational number.
396     * 
397     * @return this real rounded to the nearest integer.
398     * @throws ArithmeticException if <code>this.isNaN()</code>
399     */
400    public LargeInteger round() {
401        if (this == NaN)
402            throw new ArithmeticException("Cannot convert NaN to integer value");
403        LargeInteger half = LargeInteger.FIVE.times10pow(_exponent - 1);
404        return isNegative() ? _significand.minus(half).times10pow(_exponent) :
405            _significand.plus(half).times10pow(_exponent);
406    }
407
408    /**
409     * Returns the negation of this real number.
410     * 
411     * @return <code>-this</code>.
412     */
413    public Real opposite() {
414        if (this == NaN)
415            return NaN;
416        Real real = FACTORY.object();
417        real._significand = _significand.opposite();
418        real._exponent = _exponent;
419        real._error = _error;
420        return real;
421    }
422
423    /**
424     * Returns the sum of this real number with the one specified.
425     * 
426     * @param that the real to be added.
427     * @return <code>this + that</code>.
428     */
429    public Real plus(Real that) {
430        if ((this == NaN) || (that == NaN))
431            return NaN;
432        if (this._exponent > that._exponent)
433            return that.plus(this); // Adds to the real with smallest exponent. 
434        int scale = that._exponent - this._exponent; // >= 0
435        Real real = FACTORY.object();
436        real._exponent = _exponent;
437        real._significand = this._significand.plus(that._significand.times10pow(scale));
438        real._error = this._error.plus(that._error.times10pow(scale));
439        return real.normalize();
440    }
441
442    /**
443     * Returns the difference between this real number and the one
444     * specified.
445     * 
446     * @param that the real to be subtracted.
447     * @return <code>this - that</code>.
448     */
449    public Real minus(Real that) {
450        return this.plus(that.opposite());
451    }
452
453    /**
454     * Returns the product of this real number with the specified 
455     * <code>long</code> multiplier.
456     * 
457     * @param multiplier the <code>long</code> multiplier.
458     * @return <code>this · multiplier</code>.
459     */
460    public Real times(long multiplier) {
461        if (this == NaN)
462            return NaN;
463        Real real = FACTORY.object();
464        real._exponent = this._exponent;
465        real._significand = this._significand.times(multiplier);
466        real._error = this._error.times(multiplier);
467        return real.normalize();
468    }
469
470    /**
471     * Returns the product of this real number with the one specified.
472     * 
473     * @param that the real multiplier.
474     * @return <code>this · that</code>.
475     */
476    public Real times(Real that) {
477        if ((this == NaN) || (that == NaN))
478            return NaN;
479        long exp = ((long) this._exponent) + that._exponent;
480        if (exp > Integer.MAX_VALUE || (exp < Integer.MIN_VALUE))
481            return NaN; // Exponent overflow.
482        LargeInteger thisMin = this._significand.minus(this._error);
483        LargeInteger thisMax = this._significand.plus(this._error);
484        LargeInteger thatMin = that._significand.minus(that._error);
485        LargeInteger thatMax = that._significand.plus(that._error);
486        LargeInteger min, max;
487        if (thisMin.compareTo(thisMax.opposite()) > 0) {
488            if (thatMin.compareTo(thatMax.opposite()) > 0) {
489                min = thisMin.times(thatMin);
490                max = thisMax.times(thatMax);
491            } else {
492                min = thisMax.times(thatMin);
493                max = thisMin.times(thatMax);
494            }
495        } else {
496            if (thatMin.compareTo(thatMax.opposite()) > 0) {
497                min = thisMin.times(thatMax);
498                max = thisMax.times(thatMin);
499            } else {
500                min = thisMax.times(thatMax);
501                max = thisMin.times(thatMin);
502            }
503        }
504        Real real = FACTORY.object();
505        real._exponent = (int) exp;
506        real._significand = min.plus(max).shiftRight(1);
507        real._error = max.minus(min);
508        return real.normalize();
509    }
510
511    /**
512     * Returns this real number divided by the specified <code>int</code>
513     * divisor.  
514     * 
515     * @param divisor the <code>int</code> divisor.
516     * @return <code>this / divisor</code>
517     */
518    public Real divide(long divisor) {
519        return this.divide(Real.valueOf(divisor));
520    }
521
522    /**
523     * Returns this real number divided by the one specified.
524     * 
525     * @param that the real divisor.
526     * @return <code>this / that</code>.
527     * @throws ArithmeticException if <code>that.equals(ZERO)</code>
528     */
529    public Real divide(Real that) {
530        return this.times(that.inverse());
531    }
532
533    /**
534     * Returns the reciprocal (or inverse) of this real number.
535     *
536     * @return <code>1 / this</code>.
537     */
538    public Real inverse() {
539        if ((this == NaN) || (this == ZERO))
540            return NaN;
541        if (this.isExact())
542            return this.toInexact().inverse();
543        LargeInteger thisMin = this._significand.minus(this._error);
544        LargeInteger thisMax = this._significand.plus(this._error);
545        if (thisMin.isNegative() && thisMax.isPositive()) // Encompasses 0
546            return NaN;
547        int digits = MathLib.max(thisMin.digitLength(), thisMax.digitLength());
548        long exp = ((long) -this._exponent) - digits - digits;
549        if ((exp > Integer.MAX_VALUE || (exp < Integer.MIN_VALUE)))
550            return NaN; // Exponent overflow.
551        LargeInteger min = div(2 * digits, thisMax);
552        LargeInteger max = div(2 * digits, thisMin);
553        Real real = FACTORY.object();
554        real._exponent = (int) exp;
555        real._significand = min.plus(max).shiftRight(1);
556        real._error = max.minus(min).plus(LargeInteger.ONE);
557        return real.normalize();
558    }
559
560    private static LargeInteger div(int exp, LargeInteger significand) {
561        int expBitLength = (int) (exp * DIGITS_TO_BITS);
562        int precision = expBitLength - significand.bitLength() + 1;
563        LargeInteger reciprocal = significand.inverseScaled(precision);
564        LargeInteger result = reciprocal.times10pow(exp);
565        return result.shiftRight(expBitLength + 1);
566    }
567
568    private static final double DIGITS_TO_BITS = MathLib.LOG10 / MathLib.LOG2;
569
570    private Real toInexact() {
571        int digits = _significand.digitLength();
572        int scale = Real.getExactPrecision() - digits + 1;
573        Real z = FACTORY.object();
574        z._significand = _significand.times10pow(scale);
575        z._error = LargeInteger.ONE;
576        z._exponent = _exponent - scale;
577        return z;
578    }
579
580    /**
581     * Returns the absolute value of this real number.
582     * 
583     * @return <code>|this|</code>.
584     */
585    public Real abs() {
586        return _significand.isNegative() ? this.opposite() : this;
587    }
588
589    /**
590     * Compares the absolute value of two real numbers.
591     *
592     * @param that the real number to be compared with.
593     * @return <code>|this| > |that|</code>
594     */
595    public boolean isLargerThan(Real that) {
596        return this.abs().compareTo(that.abs()) > 0;
597    }
598
599    /**
600     * Returns the square root of this real number, the more accurate is this 
601     * real number, the more accurate the square root. 
602     * 
603     * @return the positive square root of this real number.
604     */
605    public Real sqrt() {
606        if (this == NaN)
607            return NaN;
608        if (this.isExact())
609            return this.toInexact().sqrt();
610        LargeInteger thisMin = this._significand.minus(this._error);
611        LargeInteger thisMax = this._significand.plus(this._error);
612        if (thisMin.isNegative())
613            return NaN;
614        int exponent = _exponent >> 1;
615        if ((_exponent & 1) == 1) { // Odd exponent.
616            thisMin = thisMin.times10pow(1);
617            thisMax = thisMax.times10pow(1);
618        }
619        LargeInteger minSqrt = thisMin.sqrt();
620        LargeInteger maxSqrt = thisMax.sqrt().plus(LargeInteger.ONE);
621        LargeInteger sqrt = minSqrt.plus(maxSqrt).shiftRight(1);
622        Real z = FACTORY.object();
623        z._significand = sqrt;
624        z._error = maxSqrt.minus(sqrt);
625        z._exponent = exponent;
626        return z.normalize();
627    }
628
629    /**
630     * Returns the decimal text representation of this number.
631     *
632     * @return the text representation of this number.
633     */
634    public Text toText() {
635        if (this == NaN)
636            return Text.valueOf("NaN");
637        if (isExact()) {
638            return (_exponent == 0) ? _significand.toText() : 
639                _significand.toText().plus("E").plus(Text.valueOf(_exponent));
640        }
641        int errorDigits = _error.digitLength();
642        LargeInteger m = (_significand.isPositive()) ? _significand.plus(FIVE
643                .times10pow(errorDigits - 1)) : _significand.plus(MINUS_FIVE
644                .times10pow(errorDigits - 1));
645        m = m.times10pow(-errorDigits);
646        int exp = _exponent + errorDigits;
647        Text txt = m.toText();
648        int digits = (m.isNegative()) ? txt.length() - 1 : txt.length();
649        if (digits > 1) {
650            if ((exp < 0) && (-exp < digits)) {
651                txt = txt.insert(txt.length() + exp, Text.valueOf('.'));
652            } else { // Scientific notation.
653                txt = txt.insert(txt.length() - digits + 1, Text.valueOf('.'));
654                txt = txt.concat(Text.valueOf('E')).concat(
655                        Text.valueOf(exp + digits - 1));
656            }
657        } else {
658            txt = txt.concat(Text.valueOf('E')).concat(Text.valueOf(exp));
659        }
660        return txt;
661    }
662
663    /**
664     * Compares this real number against the specified object.
665     * 
666     * <p>Note: This method returns <code>true</code> if <code>this</code> or 
667     *          <code>that</code> {@link #isNaN is Not-A-Number}, even though
668     *          <code>Double.NaN == Double.NaN</code> has the value
669     *          <code>false</code>.</p>
670     *
671     * @param that the object to compare with.
672     * @return <code>true</code> if the objects are two reals with same 
673     *        significand, error and exponent;<code>false</code> otherwise.
674     */
675    public boolean equals(Object that) {
676        if (this == that)
677            return true;
678        if (!(that instanceof Real))
679            return false;
680        Real thatReal = (Real) that;
681        return this._significand.equals(thatReal._significand)
682                && this._error.equals(thatReal._error)
683                && (this._exponent == thatReal._exponent);
684    }
685
686    /**
687     * Returns the hash code for this real number.
688     * 
689     * @return the hash code value.
690     */
691    public int hashCode() {
692        return _significand.hashCode() + _error.hashCode() + _exponent * 31;
693    }
694
695    /**
696     * Returns the value of this real number as a <code>long</code>.
697     * 
698     * @return the numeric value represented by this real after conversion
699     *         to type <code>long</code>.
700     */
701    public long longValue() {
702        return (long) doubleValue();
703    }
704
705    /**
706     * Returns the value of this real number as a <code>double</code>.
707     * 
708     * @return the numeric value represented by this real after conversion
709     *         to type <code>double</code>.
710     */
711    public double doubleValue() {
712        if (this == NaN)
713            return Double.NaN;
714        if (this == ZERO)
715            return 0.0;
716        // Shift the significand to a >18 digits integer (long compatible).
717        int nbrDigits = _significand.digitLength();
718        int digitShift = nbrDigits - 18;
719        long reducedSignificand = _significand.times10pow(-digitShift).longValue();
720        int exponent = _exponent + digitShift;
721        return MathLib.toDoublePow10(reducedSignificand, exponent);
722    }
723
724    /**
725     * Compares two real numbers numerically.
726     * 
727     * @param that the real to compare with.
728     * @return -1, 0 or 1 as this real is numerically less than, equal to,
729     *         or greater than <code>that</code>.
730     * @throws ClassCastException <code>that</code> is not a {@link Real}.
731     */
732    public int compareTo(Real that) {
733        Real diff = this.minus(that);
734        if (diff.isPositive()) {
735            return 1;
736        } else if (diff.isNegative()) {
737            return -1;
738        } else {
739            return 0;
740        }
741    }
742
743    /**
744     * Normalizes this real (maintains error less than 31 bits).
745     * 
746     * @return the normalized real.
747     */
748    private Real normalize() {
749        int digitError = this._error.digitLength();
750        int scale = 9 - digitError;
751        if (scale >= 0) return this; // Small error.
752        Real z = FACTORY.object();
753        z._significand = _significand.times10pow(scale);
754        z._error = _error.times10pow(scale).plus(LargeInteger.ONE);
755        z._exponent = _exponent - scale;
756        return z;
757    }
758                
759    @Override
760    public Real copy() {
761        if (this == NaN) return NaN; // Maintains unicity.
762        return Real.valueOf(_significand.copy(), getError(), _exponent);
763    }
764
765    /**
766     * Holds the factory constructing real instances.
767     */
768    private static final ObjectFactory<Real> FACTORY = new ObjectFactory<Real>() {
769
770        protected Real create() {
771            return new Real();
772        }
773    };
774
775    private static final LargeInteger FIVE;
776
777    private static final LargeInteger MINUS_FIVE;
778
779    static { // Immortal memory allocation.
780        HeapContext.enter();
781        try {
782            ZERO = Real.valueOf(0);
783            ONE = Real.valueOf(1);
784            FIVE = LargeInteger.valueOf(5);
785            MINUS_FIVE = LargeInteger.valueOf(-5);
786        } finally {
787            HeapContext.exit();
788        }
789    }
790
791    private static final long serialVersionUID = 1L;
792}