View previous topic :: View next topic |
Author |
Message |
JerryR
Joined: 07 Feb 2008 Posts: 167
|
pwr(x,y) error |
Posted: Mon Aug 10, 2020 10:52 am |
|
|
Anyone notice that pwr(x,y) evaluates inaccurately at higher values of y?
For instance: (int32)pwr(10,7)= 9999997 instead of 10000000.
Using PIC18F25K20, with compiler version 5.093.
Any workaround or solution?
Thanks! |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19512
|
|
Posted: Mon Aug 10, 2020 11:06 am |
|
|
Remember this is being done using logarithms to allow support for things
like fractional powers. Using fp numbers there are only 6 actual significant
digits in an fp number. Result it's always going to give errors like this.
Solutions. Well for a positive power, using integers, just multiply using
integers. 10*10*10*10*10*10*10 done using int32 arithmetic, will take
less time that pow(10,7), and give an accurate result.
Beyond this, a PIC24/30/33 supports 'double' fp maths, and this should give
a better result. |
|
|
JerryR
Joined: 07 Feb 2008 Posts: 167
|
|
Posted: Mon Aug 10, 2020 11:14 am |
|
|
Ttelmah:
Hi Thanks for the quick reply. Yes, I though that's the case. I'll use your "work-around, thanks. The pwr(x,y) method would have made my code a lot slimmer.
All the best |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19512
|
|
Posted: Mon Aug 10, 2020 11:50 am |
|
|
If your power is always of 10, then why not just have a lookup table?.
Code: |
const unsigned int32 powers10[] = {0, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000};
//Then:
powers10[7];
//is 10^7 etc...
|
|
|
|
JerryR
Joined: 07 Feb 2008 Posts: 167
|
|
Posted: Mon Aug 10, 2020 11:57 am |
|
|
Ahhh, clever. Thanks! |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19512
|
|
Posted: Mon Aug 10, 2020 12:00 pm |
|
|
Hundreds of times faster and smaller. |
|
|
JerryR
Joined: 07 Feb 2008 Posts: 167
|
|
Posted: Mon Aug 10, 2020 12:56 pm |
|
|
One little change, however. 10^0= 1.
const unsigned int32 powers10[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000};
Thanks again, good solution! |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19512
|
|
Posted: Tue Aug 11, 2020 1:11 am |
|
|
I'm sure I typed '1'!....
Silly billy. |
|
|
|