working with decimals

skidds

New Member
I have been studying and I understand how to do calculations that get around the inability of the PIC to do floating point math. What I haven't yet discovered is what the PIC does with the results that are obviously decimals. Everything I have read leads me to believe that all variables must be in integer form. am I wrong, or is there a way around this?
 

Fowkc

Senior Member
Anything will be rounded down to the nearest integer, so yes, any number will be in integer form. You can get round this to an extent by storing number such as 10.5 as 105 and doing all maths based on that number. When you need to display the number, just add the decimal point then, in whatever way your display requires.
 

moxhamj

New Member
Everything is in integer form but this doesn't really matter for most calculations. Do all the maths in word variables and keep all values under 65535. Eg to divide 70 by 6 the answer is 11.666 recurring. Instead, multiply the 70 by 100 to get 7000 and divide 7000 by 6 to get 1166.666 recurring which is rounded in integer to 1166. Now display with a decimal shifted two places over (ie divide by 100) and it will display as 11.66.

What the picaxe does with the decimals is it ignores them. Eg an answer of 11.6666 will be given as 11.0 This means that in integer maths an answer of 11.99 will also come back as 11.0 even though in maths one usually rounds 11.49 to 11 and 11.51 to 12. So to really be pedantic sometimes one needs to add this 0.5 on in some way usually at the beginning of the calculation. It depends on how accurate you want an answer to be. What is the calculation you are doing?
 

skidds

New Member
So , if I want to maintain a certain accuracy, I simply start by multiplying by a factor of 10, 100,1000 etc. Sounds so simple I feel stupid. I have looked into FPU's but I think I need to work up to it. Thanks for the info
 

moxhamj

New Member
Yes, though you can't multiply by 1000 if the answer goes over 65,535. There are techniques for combining two words together to make a 'long integer' and in fact, most of us learnt those techniques in grade 3 maths (carry, borrow etc) but it does add to code complexity. Sometimes there is no point going beyond a certain level of accuracy because a sensor has limited accuracy. There usually is a cunning way through the problem within the limitations of integer maths.
 

Brietech

Senior Member
I think someone actually *DID* come up with a floating point routine for the picaxe a while ago (someone named brian something, perhaps?), although I'm not sure how much space it took up.
 
Top