Mod of negative values

Questions and discussion about the ZBasic IDE.
Post Reply
GTBecker
Posts: 616
Joined: 17 January 2006, 19:59 PM
Location: Cape Coral

Mod of negative values

Post by GTBecker »

Paul's last message spurred a question I failed to ask some time ago.

Consider:

Code: Select all

Sub Main()
   console.writeline(cstr(-90.0 mod 360.0))                                                                                     
End Sub
A practical application of this is counterclockwise rotation of a shaft that points to a degree wheel. -90 degrees from 0.0/+360.0 is +270.0 degrees in practice. What is the rationale of yielding -90.0 for (-90.0 mod 360.0)?


Tom
Tom
mikep
Posts: 796
Joined: 24 September 2005, 15:54 PM

Post by mikep »

Depending on the programming language concerned the modulus operator takes either the sign of the divisor or the sign of the dividend. As ZBasic is derived from Visual Basic, it uses the same scheme as Visual Basic which is to use the sign of the dividend. Therefore taking the modulus of any negative number in ZBasic results in a negative result.
Mike Perks
dkinzer
Site Admin
Posts: 3120
Joined: 03 September 2005, 13:53 PM
Location: Portland, OR

Post by dkinzer »

mikep wrote:As ZBasic is derived from Visual Basic, it uses the same scheme as Visual Basic which is to use the sign of the dividend.
Just so. It is unfortunate that BasicX, which also derives from Visual Basic, returns a positive result. When we were implementing ZBasic, we had to choose whether it was more important to be compatible with VB or BasicX. In this particular case we opted for VB compatibility and noted the difference in the Compatibility Issues section of the ZBasic Reference Manual.

Regarding your specific use case, you can get a result in the 0-360 range using the idiom below.

Code: Select all

result = ((angle Mod 360.0) + 360.0) Mod 360.0
- Don Kinzer
Post Reply