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
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