Page 1 of 1

Calculation order

Posted: Mon Jan 04, 2021 4:47 pm
by mnfisher
Not sure if this has been reported before - but it's just caused me some debug grief.

Trying out an algorithm in the simulator I have

Code: Select all

.Return = .a + .b / 2
Which on hardware I would expect to give the answer, say for .a = 10 and .b = 20, of 15..

In the simulator it doesn't - it gives 25 (so it's doing .Return = .a + (.b / 2))

Tested under v8 and it's also a problem there.
bodmas.fcfx
(7.2 KiB) Downloaded 601 times
Martin

Re: Calculation order

Posted: Mon Jan 04, 2021 5:58 pm
by Steve-Matrix
I think that's correct. in BODMAS, the "D" (divide) takes precedence over the "A" (add).

So

Code: Select all

z = a + b / c 
will be calculated as

Code: Select all

z = a + (b / c)

Re: Calculation order

Posted: Mon Jan 04, 2021 6:00 pm
by kersing
Sounds like perfect order in which the operands should be applied to me.
Division has higher priority and is performed first. If you want to make sure things are done in the order you expect always use parenthesis.

Re: Calculation order

Posted: Mon Jan 04, 2021 6:34 pm
by mnfisher
Yes - having a bad day on the math front! :oops: what a numpty....

It is (of course) doing it perfectly and my brain isn't.....
What I wanted was (.a + .b) / 2 and that was what I used in the end... Sadly .Return = 0 would have probably worked just as well ;)
(see https://www.matrixtsl.com/mmforums/view ... 26&t=20604)


Martin

Re: Calculation order

Posted: Mon Mar 06, 2023 11:25 am
by Lesteraction
Division is completed first since it is more important. Always use parentheses if you want to ensure that things are completed in the sequence you anticipate.