Finding the difference between two numbers

inglewoodpete

Senior Member
From time to time I want to find the difference between two numbers. It doesn't matter which one is smaller or larger, just the difference.

I usually write code like this.
Code:
[color=Blue]If [/color][color=Purple]w10 [/color][color=DarkCyan]> [/color][color=Purple]w11 [/color][color=Blue]Then
   [/color][color=Purple]w12 [/color][color=DarkCyan]= [/color][color=Purple]w10 [/color][color=DarkCyan]- [/color][color=Purple]w11[/color]
[color=Blue]Else
   [/color][color=Purple]w12 [/color][color=DarkCyan]= [/color][color=Purple]w11 [/color][color=DarkCyan]- [/color][color=Purple]w10   [/color][color=Green]'w12 will equal 0 if w10 & w11 are equal[/color]
[color=Blue]EndIf[/color]
I could write a macro, of course, to hide the cumbersome code but is there a nifty one-line piece of code that I could use instead?
 

hippy

Technical Support
Staff member
No true one-liner I can think of but this will do the job without an IF ...

Code:
w12 = w10 Max w11
w12 = w10 Min w11 - w12
MAX and MIN are limiting operations so MAX returns the lowest of two numbers, MIN returns the highest of two numbers.
 

inglewoodpete

Senior Member
Thanks hippy, Another gem from your arsenal. Perhaps a "DIF" command could be added to the X3 range, when they arrive ;).

The function is useful when interfacing to the real world where "near enough is close enough".
 
Last edited:

hippy

Technical Support
Staff member
If "close enough" was a difference of 5 or less say, then I’d use the following:-
Because of the way PICAXE handles numbers, if w10=65535, w11=0, then w10-w11+5 would give a result of 4 which isn't correct.
 

BillBWann

Member
Because of the way PICAXE handles numbers, if w10=65535, w11=0, then w10-w11+5 would give a result of 4 which isn't correct.
I assumed that inglewoodpete was comparing some measured parameter which he was controlling against a given setpoint (say a GPS coordinate of a vehicle against a way point coordinate) and that he would have chosen values for those parameters which wouldn't be in danger of overflowing in his real world situation.
 
Top