Shop OBEX P1 Docs P2 Docs Learn Events
Question about Negative numbers — Parallax Forums

Question about Negative numbers

HI, I have a question about calculation of negative numbers. Below is a easy code shows the problem that I occurred:

' {$STAMP BS2}
' {$PBASIC 2.5}
Result VAR Word
tilt VAR Word
tilt = 500
Result=(tilt-750)/3
DEBUG SDEC ? Result
DEBUG SDEC ? ABS Result
As we know, Result here should be -83.33, which is negative. But the DEBUG shoes the Result is 21762. I think it might be some problem with 2's complements, but I don't know how exactly solve it. Can anyone help me? Thanks guys!

Comments

  • Page 113 of the BS manual says that division only works with positive numbers.
    A workaround to the inability to divide signed numbers is to have your
    program divide absolute values, then negate the result if one (and only
    one) of the operands was negative. All values must lie within the range of
    -32767 to +32767. Here is an example:
    
    sign VAR Bit ' Bit to hold the result sign
    value1 VAR Word
    value2 VAR Word
    
    value1 = 100
    value2 = -3200
    
    sign = value1.BIT15 ^ value2.BIT15 ' Determine sign of result
    value2 = ABS value2 / ABS value1 ' Divide absolute values
    IF (sign = 1) THEN value2 = -value2 ' Negate result if sign = 1
    DEBUG SDEC ? value2 ' Show the result (-32)
    
  • If tilt is positive, another way to deal with that sort of problem is to divide before the subtraction:
    Result=(tilt/3-250)
    Or, if tilt can go negative, say, a minimum of -1500:
    Result=((tilt+1500)/3-750)

    Multiplication is okay with twos complement, so long as the result does not overflow the -32768 to +32767 limits. So another way is to multiply instead of divide, approximately:
    Resultx10=(tilt-750)*33
    okay so long as tilt is in the range -242<tilt<992.



Sign In or Register to comment.