picaxe friendly maths

Mike_cj0

Member
I imagine this is probably very simple to sort but i have been racking my brains for a while now and not getting anywhere useful!

basically what i would like to achieve is

w1 = w2 * 1.5

Im sure this must be blindingly obvious and easy to solve but i just can see the wood for the trees!

Sorry for the stupid question!

Mike
 

alband

Senior Member
I've tested an AXE's rounding capabilities and they're not great!
Do any divisions second so that your number will be rounded at the end of the process.
 

papaof2

Senior Member
Since the PICAXE line only supports integer math, you must be creative to do the equivalent of a floating point operation. If small errors are acceptable in your application, there are relatively simple ways to do this.

If you don't know the maximum value of w2:
w1 = w2 / 2
w1 = w1 * 3

Example:
10 / 2 = 5
5 * 3 = 15

If you know that the maximum value of w2 will always be less than 21000:
w1 = w2 * 3
w1 = w1 / 2

Example:
10 * 3 = 30
30 / 2 = 15

You do need to watch for overflow, as a word has a maximum value of 65535.

There is the potential for a loss of accuracy with the first code: if w1 contains an odd number, the fraction is lost.

Example:
17 * 1.5 = 25.5
17 / 2 = 8 (integer math, fractions are lost)
8 * 3 = 24

The second code example is better:
17 * 3 = 51
51 / 2 = 25 (integer math, no fractions)

If you need true floating point, there is a math chip available to work with the PICAXE.

You might also try a Forum search for
float
floating

Someone else may have a better way of doing this.

John
 

Jeremy Leach

Senior Member
Actually guys a better way might be: w1 = w2/2 + w2

ie add half of w2 to w2. The advantage of doing it this way is that you are not going to get overflow, unless the result itself is bigger than a word.
 

westaust55

Moderator
If you do not need to keep the original value it can also be done with one variable and that saves the very limited number of variables.

w2 = w2 * 3 / 2 ; for values of w2 less than 21845

or

w2 = w2/2 + w2 ; for values of w2 less than 43690
 

westaust55

Moderator
Note that since there is not mathematical precedence in the PICAXE (still to come for X1 and later parts) the command sequence must be done in the order that Jeremy gave.

Namely: w2 = w2/2 + w2

If it is rotated to be w2 = w2 + w2/2
then you will end up with the original value, that is it equates to: w2 = w2
 
Top