Integer Division not correct?

Archives Forums/Blitz3D Bug Reports/Integer Division not correct?

BladeRunner(Posted 2010) [#1]
Try this Code:


Seems there is a bug in dividing negative Integers by constant values which are powers of two.


_PJ_(Posted 2010) [#2]
What's the problem?


Dreamora(Posted 2010) [#3]
that it does not consistently return 0 as it should with int divisions where the divisor is larger than the divided value

likely an shl - shr optimization that messes up


BladeRunner(Posted 2010) [#4]
Run the program and check the results: dividing a negative by a power-of-2-constant gives wrong results. -1 instead of 0.


Silver_Knee(Posted 2010) [#5]
it could be an approximating problem. I can remember reading in an Language reference Blitz approximate to the next "power of 2"-number. so 0.5 -> 0 and 1.5 -> 2. Maybe this affects here to.


_PJ_(Posted 2010) [#6]
It is due to approximation as Silver_Knee states, and not a bug.

Also it is coding issue. For integer math
Bla/2
is better defined as (Int(Bla%*0.5))


Floyd(Posted 2010) [#7]
It is definitely a bug.

I have no idea why it hasn't been fixed. It works properly in BlitzMax.


_PJ_(Posted 2010) [#8]
It's down to the declaration and whether or not the code is written to 'confuse' the compiler by mixing up integral, byte or floating point comparisons.

Bla = -1
Ble%=-1
Const Blo=-1
Blf#=-1.0

Print Bla/2
Print Bla*0.5
Print Bla Shr 1

Print

Print Int(Ble%/2)
Print Int(Ble%*0.5)
Print Int(Ble% Shr 1)

Print

Print Blo/2
Print Blo*0.5
Print Blo Shr 1

Print

Print Blf#/2.0
Print Blf#*0.5
Print Float(Blf# Shr 1.0)




Floyd(Posted 2010) [#9]
There is nothing to confuse. This is simple integer arithmetic. Bytes and floats are not involved.

The fact that constants and variables give different results tells you something is wrong. In fact Blitz is optimizing division by a power of 2, replacing it with a sign-preserving shift. This is off by 1 when done with negative numbers.


TheSkyIsUp(Posted 2010) [#10]
I also have a problem with Blitz3D division. Every time I try to divide a number by a greater number, the result is zero. I need help.

For example:

     While Not KeyDown(1)

     Print 10/20

     WaitKey()

     Wend


The answer is 0 even no matter what whenever the divider is greater.


H&K(Posted 2010) [#11]
And
Print 10.0/20.0 gives?


TheSkyIsUp(Posted 2010) [#12]
I see now that was kind of a stupid question of mine ^^;


_PJ_(Posted 2010) [#13]
There is nothing to confuse. This is simple integer arithmetic. Bytes and floats are not involved.

The fact that constants and variables give different results tells you something is wrong.

Yes, I stand corrected.

I was considering how a different syntax was interpreted differently on compilation where more bytes are used as accumulators for floating point calculations.

I would assume the bug exists in BPlus too.

At least, it's possible to workaround, though it could be ptretty damaging if not picked up.