libcg / bfp

Beyond Floating Point - Posit C/C++ implementation
MIT License
289 stars 25 forks source link

Bug when adding numbers with large difference #21

Closed Tongdongq closed 5 years ago

Tongdongq commented 5 years ago

Sorry to bother you again, I think I found a bug when adding numbers that are 10 OoMs apart: double a = 1.2e4; double b = -2.5e-6; double c; Posit pa = Posit(W, es); Posit pb = Posit(W, es); Posit pc = Posit(W, es); pa.set(a); pb.set(b); pc = pa + pb; c = a + b; pa.print(); pb.print(); pc.print(); printf("pa: %f, pb: %.7f, pc: %f\n", pa.getDouble(), pb.getDouble(), pc.getDouble()); printf("a: %f, b: %.7f, c: %f\n", a, b, c);

Output for 32,3 and 32,2: {32, 3} 01101010111011100000000000000000 -> +110 101 0111011100000000000000000 = 12000 {32, 3} 11110010101100000111010010101000 -> -0001 101 010011111000101101011000 = -2.5e-06 {32, 3} 01100100011101110100101010000000 -> +110 010 0011101110100101010000000 = 1262.58 pa: 12000.000000, pb: -0.0000025, pc: 1262.582031 a: 12000.000000, b: -0.0000025, c: 11999.999997

{32, 2} 01111001011101110000000000000000 -> +11110 01 011101110000000000000000 = 12000 {32, 2} 11111101010110000011101001010100 -> -000001 01 01001111100010110101100 = -2.5e-06 {32, 2} 01110100011101110100101010000000 -> +1110 10 0011101110100101010000000 = 1262.58 pa: 12000.000000, pb: -0.0000025, pc: 1262.582031 a: 12000.000000, b: -0.0000025, c: 11999.999997

libcg commented 5 years ago

That's actually very helpful, I can fix it and add it to the test suite to make sure it doesn't happen again. Please keep digging :+1:

libcg commented 5 years ago

Looks like 86b9cd7a0 fixed the issue, it now prints:

{32, 3} 01101010111011100000000000000000 -> +110 101 0111011100000000000000000 = 12000
{32, 3} 11110010101100000111010010101000 -> -0001 101 010011111000101101011000 = -2.5e-06
{32, 3} 01101010111011100000000000000000 -> +110 101 0111011100000000000000000 = 12000
pa: 12000.000000, pb: -0.0000025, pc: 12000.000000
a: 12000.000000, b: -0.0000025, c: 11999.999997

However, it also prints an incorrect positive pb when using getFloat():

pa: 12000.000000, pb: 0.0000025, pc: 12000.000000
a: 12000.000000, b: -0.0000025, c: 12000.000000
libcg commented 5 years ago

Fully fixed with dabfc97.