Variables - Mathematics

Jarubell

Senior Member
I have been browsing this forum looking for information on how to code some mathematics. I would like to solve something like;

(b0/255)*150

I understand Picaxe does not support fractions (and brackets (manual 2, page 25)), I just can not figure this out.
 

westaust55

Moderator
As you correctly say, PICAXE BASIC does not support fractional numbers and is yet to support brackets.
Also all maths are strictly left to right.
You simple math can be done on a single line of code. More complex calculations can require intermediate results as Oracle has shown.

Staying with simple math, there are several ways to tackle the solution to calculate your result is:
Consider that:
w5 = b0 / 255 * 150 will always give a low answer.
Options:
1. Restructure the calculation to do the multiply first
w5 = b0 * 150 / 255
This will give a closer result but still always low

2. Multiply the initial value (b0) by 10 if you want 1 decimal place or by 100 if you want 2 decimal places.
Note that this intermediate value must not exceed 65535. With a byte variable (0 to 255) this will not be a problem but it may if the starting value is a word variable (0 to 65535)
So now you calculate as:
w5 = b0 * 100 / 255 * 150 ; use a word variable (eg w5) as the answer will be greater than 255

3. Add a value in being half of the divisor to apply some rounding
So now you calculate as:
w5 = b0 * 100 +128 / 255 * 150 ; use a word variable (eg w5) as the answer will be greater than 255

To look at the accuracy lets say b0 = 10 where the correct answer is 5.88
Solution 1 gives a result of 5 (15% low)
Solution 2 gives a result of 450 which because we multiplied by 100 represents 4.50 quite (23.5%) low
Solution 3 gives a result of 600 which because we multiplied by 100 represents 6.00 so just a little (2%) high

Now look with b0 = 96 where the correct answer is 56.47
Solution 1 gives a result of 56 (0.08% low)
Solution 2 gives a result of 5550 which because we multiplied by 100 represents 55.50 a bit (1.72%) low
Solution 3 gives a result of 5700 which because we multiplied by 100 represents 57.0 so just a little (0.93%) high

Finally look with b0 = 125 where the correct answer is 73.52
Solution 1 gives a result of 73 (0.72% low)
Solution 2 gives a result of 7350 which because we multiplied by 100 represents 73.50 just a bit (0.04%) low
Solution 3 gives a result of 7350 which because we multiplied by 100 represents 73.50 just a bit (0.04%) low

In summary it depends upon the accuracy and number of decimal places ( typically 2 is max with PICAXE) needed.
You will often end up with some error with such manipulations.
 

Jarubell

Senior Member
Thank you both Oracacle and Westaust55.

Westaust55, I never expected such a detailed response, greatly appreciated.
 
Top