View previous topic :: View next topic |
Author |
Message |
guest Guest
|
Floating popint question |
Posted: Mon Mar 07, 2005 8:16 am |
|
|
Hi all.
How come when I have the following code:
Code: | a2dval = 100 /4;
lcd_gotoxy(1,2);
printf(lcd_putc,"%2.2F ", a2dval);
|
The answer is printed on the lcd as 24.99 and not 25 or 25.00.
a2dval is defined as type float.
Cheers
Rob |
|
|
Ttelmah Guest
|
|
Posted: Mon Mar 07, 2005 9:00 am |
|
|
Welcome to the delights of FP.
FP numbers are not accurate. Printf makes no attempt to round, so if the value is held as 24.999999, it will display as 24.99.
For 'better' results, use:
printf(lcd_putc,"%2.2F ", a2dval+0.0049999);
The same effect is seen, even with the much higher FP accuracy on larger computers. This is why for 'critical' applications (money!), FP, is not the format of choice. Instead a scaled integer is used, to ensure that this does not happen.
Best Wishes |
|
|
Guest Guest
|
|
Posted: Tue Mar 08, 2005 11:58 pm |
|
|
Thanks for the help.
Cheers
Rob |
|
|
Douglas Kennedy
Joined: 07 Sep 2003 Posts: 755 Location: Florida
|
|
Posted: Wed Mar 09, 2005 7:53 am |
|
|
Telemath is right when observing foating point binary is different than a decimal base 10 result. Both are accurate representations of reality in there respective bases it is the conversion from one base to another that has imprecision. Ex 1/3 can't be represented in either binary or decimal without rounding at some point. In base 3 arithmetic it is accurately represented by 0.1. 1/10 in decimal is accurate 0.1 but can only be approximated in binary. Fixed point integer ( do all the work in cents rather than $and cents) is best since CCS has it built in but your electronic calculator as well as commercial systems use BCD.
The calculator does the work as we would if we were hand calculating by breaking numbers down into columns of powers of ten and operating column by column adding and carring the remainders. In BCD a digit is stuffed into each 4 bit nibble. The PIC does have one nibble operator SWAP but I've only seen it used in restoring interrupt registers. |
|
|
|