Question about math order of operations

NVHLVNOP

Member
Let's say I have the following math operation:

FOR b0 = 0 to 255
w0 = 500 * b0 / 2
'do something here with w0
NEXT

Question: Will I have problems with w0 wrapping around back to zero once b0 gets to 132 in the loop? Does the chip calculate w0 as 500 * 132 = 66000 (which is really 464 since w0 is 16 bits), and then divide by two? Will I end up with an answer of 232, or will I end up with 500*132/2 = 33000? Two very different answers! I'm wondering if w0 stores the answer at each and every step of the calculation, or if the entire calculation is completed (without worrying about exceeding 16 bits), and then the answer is dumped into w0.

I know I can just rewrite this example as 500 / 2 * b0, or 250 * b0, but this is just an example. I can't do the same simple rewrite with my actual equation. Once again, I'm just wondering how the calculation is performed.

Thanks.
 

Svejk

Senior Member
Picaxe maths are performed strictly from left to right. Your first interpretation is corect.

Also instead of 500/2 * w0 you may use 250 * w0
 

BeanieBots

Moderator
As Svejk correctly states, Picaxe maths are performed strictly from left to right.

However, you have a major problem with that code.
Your for next loop uses b0 for its counter.
Your line "w0 = 500 * b0 / 2" will set w0 to 0 first time around.
b0 also happens to be the LSB of w0 so your loop counter will also be reset to zero and result in the for/next loop not behaving as expected.

As for the general question of what would happen with a particular sum, the quickest route to an answer would be to try it in the simulator.
 
Last edited:

NVHLVNOP

Member
Thanks guys.
BeanieBots, I'm aware of b0 being part of w0, but didn't think about it while writing out this example. Good catch!
 

westaust55

Moderator
@NVHLVNOP,

Some further clarification/expansion on the PICAXE maths.

In addiiton to maths being performed strictly from left to right (until such time as Rev Ed organise the use of parenthesis)

When performing maths, the internal intermediate maths is always to 16 bits (ie max value of 65,525).

So when multiplying ( * command ) two byte variables there would never be a problem
but when multiplying a word by a byte or multiplying two word variables together then overflow is possible and the result is the lower 16 bits.

PICAXE math (See PICAXE manual 2) does also include the ** function which can be used to obtain the upper 16 bits of an effective 32 bit value from multiplying a word by a byte or multiplying two word variables.
 
Top