1

Closed

wrong sign when adding negative numbers

description

Hi, there seems to be a misstake in the OpHelper.cs which results in wrong signs when adding a negative number to zero.
You can reproduce it with this simple C# code:
 
 
// BEGIN CODE
 
using System;
using Oyster.Math;
 
namespace Test
{
class Program
{
    static void Main(string[] args)
    {
        IntX num1 = new IntX(0);
        IntX num2 = new IntX(-1);
        IntX diff = num1 + num2;
        Console.Out.WriteLine(diff);
    }
}
}
 
// END CODE
 
 
Adding -1 to 0 should obviously return -1, but IntX returns +1.
 
As far as I could trace this issue the sign becomes inverted twice. A quick&dirty workaround is to modify the AddSub-Function in OpHelper.cs as follows:
 
 
// BEGIN CODE
 
static public IntX AddSub(IntX int1, IntX int2, bool subtract)
{
// Exceptions
if (ReferenceEquals(int1, null))
{
    throw new ArgumentNullException("int1", Strings.CantBeNull);
}
else if (ReferenceEquals(int2, null))
{
    throw new ArgumentNullException("int2", Strings.CantBeNull);
}
 
// Determine real operation type and result sign
if (subtract ^ int1._negative == int2._negative)
{
    return Add(int1, int2);
}
else
{
// Workaround DEFRODAV: Sign of second integer has to be positive before subtracting
    IntX newInt2 = new IntX(int2);
    newInt2._negative = false;
    return Sub(int1, newInt2);
}
}
 
// END CODE
 
 
This workaround works but I think it's rather a quick&dirty hack than a fix. Maybe you could investigate further and find the real reason for this issue.
Anyway, thanks a lot for creating this library, great work!
 
regards,
David
Closed Mar 12, 2010 at 1:10 PM by Oyster
Thanks for finding this bug, I've fixed it in 0.9.3.3; the real problem was in OpHelpers.Sub() method. And sorry for a big delay - for some reason issue notifications stopped arriving on my email.

comments