1

Closed

Bugs in the Pow function

description

Firstly thanks to the author for implementing a very tricky algorithm (DFT multiplication). Also the code is beautifully written in the OOP sense.
 
I'm finding that IntX.Pow(0, 0) = 0 (could be either 0 or 1 but convention nowadays more for the value 1 and this would be consistent with Math.Pow in the BCL). See also (http://mathforum.org/dr.math/faq/faq.0.to.0.power.html) if interested in why 0^0 could be either 0, 1 or NaN.
 
Also I find that IntX.Pow(N, 1) just hangs the machine (there is a bug in the main calculation loop for the power one).
 
A small re-jig of the tests for special cases at the beginning of the Pow routine can check for powers 0, 1 and then for a vaule of 0, which ensures that the results are calculated consistent with Math.Pow:
 
 
 
    static public IntX Pow(IntX value, uint power, MultiplyMode multiplyMode)
    {
        // Exception
        if (ReferenceEquals(value, null))
        {
            throw new ArgumentNullException("value");
        }
 
        // Return one for zero pow
        if (power == 0) return 1;
 
        // Return the number itself from a power of one
        if (power==1) return new IntX(value);
 
        // Return zero for a zero
        if (value._length == 0) return new IntX();
 
        // Get first one bit
        int msb = Bits.Msb(power);
 
        // Get multiplier
        IMultiplier multiplier = MultiplyManager.GetMultiplier(multiplyMode);
 
        // Do actual raising
        IntX res = value;
        for (uint powerMask = 1U << (msb - 1); powerMask != 0; powerMask >>= 1)
        {
            // Always square
            res = multiplier.Multiply(res, res);
 
            // Maybe mul
            if ((power & powerMask) != 0)
            {
                res = multiplier.Multiply(res, value);
            }
        }
        return res;
    }
Closed Jan 16, 2010 at 4:38 PM by Oyster
Thanks for reporting this issue, I have fixed it as suggested and added corresponding unit test. Fix is in release 0.9.3.

comments