integer math, where are the intermediate values stored? limitations?

Hello all,

I have what is probably a very silly question.

I have an equation say:

int result = (200 * 8 * 33) / 1000;

a signed integer can of course hold +/- 32768. 'result' should be 52 and should fit just fine. However i keep getting strange math errors in equations like this and i think it is because the (200 * 8 * 33) part if it results in 52800 which is too big to fit in the integer.

So my questions are, is my thinking correct? Is all of the intermediate arithmetic as it crunches stored in a register the same size as the data type that it will eventually be assigned to?

And how do i get around this? If i do like (200 * 8)/1000 * 33 or (200 * 33)/1000 * 8 my rounding error grows too high.

Do i just need to use a long even though i'm only storing a max of 52?

Thanks!

Is all of the intermediate arithmetic as it crunches stored in a register the same size as the data type that it will eventually be assigned to?

No. The intermediate results are stored in a register that is the size of the largest data value involved. Since all the values are ints, an int register is used. 52,800 will not fit in an int.

You can change the register size by casting or by adding L or UL to the end of one or more of the values.

ahhh, that clears it up. thanks!

int result = (200 * 8 * 33) / 1000;

You don't need the () so

int result = 200 * 8 * 33 / 1000;

would get you the same (wrong result) this is because * and / have the same presidence and therefore the expression is evaluated from left to right.

But Rearranging it to

int result = 200 * 8 * /1000 * 33 ;

should work.

Well +/- the "strange" things that integer math gets up to.

int result = 200 /1000 * 8 * 33 ;

Will get you a very different result.

Have fun

Mark

I found it easier to understand what went wrong, sorry Paul

int result = (200 * 8 * 33) / 1000

200833 is computated before the division, therefore as we now know, 52,800 is not an integer.

JB_AU:
I found it easier to understand what went wrong, sorry Paul

int result = (200 * 8 * 33) / 1000

200833 is computated before the division, therefore as we now know, 52,800 is not an integer.

To be precise, 52,800 is an integer. It just won't fit into an integer variable.

To be precise, 52,800 is an integer. It just won't fit into an integer variable.

That isn't precise at all.
It won't fit into an "int" variable on any Arduino except the Due.
However, don't confuse "int" with "integer" long myVar = 52800;

Another choice is to scale some of your data:

int result = (2 * 8 * 33) / 10;

No need to multiply by an extra factor of 100 and then divide by 1000.