( A + B ) Max M

hippy

Technical Support
Staff member
Sometimes it is desirable to perform a calculation such as ...

result = ( A + B ) Max M

Unfortunately A + B may generate a result which is greater than 65535 and cause an overflow which is less than M.

However, if 'B' is limited to being no more than 'M-A', there never can be a result greater than M, providing that A is never allowed to become greater than M ...

result = A + ( B Max (M-A) )

Both 'x + y' and 'x Max y' are commutative; x and y can be swapped and it still gives the same result so ...

result = A + ( B Max (M-A) )
result = A + ( (M-A) Max B )
result = ( (M-A) Max B ) + A

Or in PICAXE maths ...

result = M - A Max B + A


If there is a possibility that A may be greater than M the easiest solution is to ensure A is limited to M before performing the calculation ...

A = A Max M
result = M - A Max B + A
 

fernando_g

Senior Member
WOW!

This is a simple, yet quite profound insight.

Thanks for sharing, I hadn't had the need to use it, but if I had, I would have used the incorrect way and never know how come the results were incorrect.
 
Top