Integer Division not correct?Archives Forums/Blitz3D Bug Reports/Integer Division not correct?
| Try this Code:|
Seems there is a bug in dividing negative Integers by constant values which are powers of two.
| What's the problem? |
| 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
| Run the program and check the results: dividing a negative by a power-of-2-constant gives wrong results. -1 instead of 0. |
| 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. |
| It is due to approximation as Silver_Knee states, and not a bug.|
Also it is coding issue. For integer math
is better defined as (Int(Bla%*0.5))
| It is definitely a bug. |
I have no idea why it hasn't been fixed. It works properly in BlitzMax.
| 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)
| 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.
| 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.|
While Not KeyDown(1) Print 10/20 WaitKey() Wend
The answer is 0 even no matter what whenever the divider is greater.
| And |
Print 10.0/20.0 gives?
| I see now that was kind of a stupid question of mine ^^; |
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.