Example #1
0
        /** Return this raised to an integer power.
         * Implemented by repeated squaring and multiplication.
         * If y < 0, returns div_inv of the result. */
        public virtual Numeric power(IntNum y)
        {
            if (y.isNegative())
            {
                return(power(IntNum.neg(y)).div_inv());
            }
            Numeric pow2 = this;
            Numeric r    = null;

            for (;;)  // for (i = 0;  ; i++)
            {
                // pow2 == x**(2**i)
                // prod = x**(sum(j=0..i-1, (y>>j)&1))
                if (y.isOdd())
                {
                    r = r == null ? pow2 : r.mul(pow2);       // r *= pow2
                }
                y = IntNum.shift(y, -1);
                if (y.isZero())
                {
                    break;
                }
                // pow2 *= pow2;
                pow2 = pow2.mul(pow2);
            }
            return(r == null?mul_ident() : r);
        }
Example #2
0
        public static RatNum make(IntNum num, IntNum den)
        {
            IntNum g = IntNum.gcd(num, den);

            if (den.isNegative())
            {
                g = IntNum.neg(g);
            }
            if (!g.isOne())
            {
                num = IntNum.quotient(num, g);
                den = IntNum.quotient(den, g);
            }
            return(den.isOne() ? (RatNum)num : (RatNum)(new IntFraction(num, den)));
        }
Example #3
0
        public override double doubleValue()
        {
            bool neg = num.isNegative();

            if (den.isZero())
            {
                return(neg ? Double.NegativeInfinity
                        : num.isZero() ? Double.NaN
                        : Double.PositiveInfinity);
            }
            IntNum n = num;

            if (neg)
            {
                n = IntNum.neg(n);
            }
            int num_len = n.intLength();
            int den_len = den.intLength();
            int exp     = 0;

            if (num_len < den_len + 54)
            {
                exp = den_len + 54 - num_len;
                n   = IntNum.shift(n, exp);
                exp = -exp;
            }

            // Divide n (which is shifted num) by den, using truncating division,
            // and return quot and remainder.
            IntNum quot      = new IntNum();
            IntNum remainder = new IntNum();

            IntNum.divide(n, den, quot, remainder, TRUNCATE);
            quot      = quot.canonicalize();
            remainder = remainder.canonicalize();

            return(quot.roundToDouble(exp, neg, !remainder.isZero()));
        }
Example #4
0
 public static IntFraction neg(IntFraction x)
 {
     // If x is normalized, we do not need to call RatNum.make to normalize.
     return(new IntFraction(IntNum.neg(x.numerator()), x.denominator()));
 }