(See PBASIC Operators for a complete list of all PBASIC operators, with links to explanations of each.)
The BASIC Stamp solves math problems in the order they are written; from left to right. The result of each operation is fed into the next operation. So to compute:
12 + 3 * 2 / 4
...the BASIC Stamp goes through a sequence like this:
12 + 3 = 15
15 * 2 = 30
30 / 4 = 7
Note that since the BASIC Stamp performs integer math (whole numbers only) 30 / 4 results in 7, not 7.5.
Some other dialects of BASIC would compute that same expression based on their precedence of operators, which requires that multiplication and division be done before addition. So the result would be:
3 * 2 = 6
6 / 4 = 1
12 + 1 = 13
Once again, because of integer math, the fractional portion of 6 / 4 is dropped, so we get 1 instead of 1.5.
Unary operators (those with one argument) take precedence over binary operators (those with two arguments); the unary operation is always performed first. For example, on all BS2 models, SQR is the unary operator for square root. In the expression:
10 - SQR 16
...the BASIC Stamp first takes the square root of 16, then subtracts it from 10.
The BS1 does not allow parentheses in expressions. Unfortunately, all expressions have to be written so that they evaluate as intended strictly from left to right. The negative operator is the only unary operator for the BS1.
The BS2 family modules, however, allow parentheses to be used to change the order of evaluation. Enclosing a math operation in parentheses gives it priority over other operations. To make the BASIC Stamp compute the previous expression in the conventional way, you would write it as 12 + (3 * 2 / 4). Within the parentheses, the BASIC Stamp works from left to right. If you wanted to be even more specific, you could write 12 + ((3 * 2) / 4). When there are parentheses within parentheses, the BASIC Stamp works from the innermost parentheses outward. Parentheses placed within parentheses are called nested parentheses.
The BASIC Stamp performs all math operations by the rules of positive integer math. That is, it handles only whole numbers, and drops any fractional portions from the results of computations. The BASIC Stamp handles negative numbers using two's complement rules.
All BS2 models can interpret two's complement negative numbers correctly in DEBUG and SEROUT instructions using formatters like SDEC (for signed decimal). In calculations, however, it assumes that all values are positive. This yields correct results with two's complement negative numbers for addition, subtraction, and multiplication, but not for division.
BASIC Stamp Help Version 2.5.4
Copyright © Parallax Inc.
8/8/2012