Calculating pow with doubles gives wrong results

369 views Asked by At

I'm programming a calculator on an Arduino and I'm trying to calculate pow and writing it to a string (result). This is my code:

dtostrf(exp(n*log(x)), 0, 5, result); // x ^ n

2 ^ 2 = 4.00000 // works fine

10 ^ 5 = 99999.9770 // should be 100000

What's wrong with my code and how can I always get the right result? I mean how can I round it but still be able to use doubles ( e.g. 5.2 ^ 3.123 )

2

There are 2 answers

3
chiastic-security On BEST ANSWER

You're just hitting rounding errors. There's nothing you can do about this, except revert to an integer-based approach whenever the inputs are integers.

You could condition on whether the inputs are integers, and if so then use integer arithmetic; if not, then use doubles. But using exp and log will always introduce rounding errors, so you can't expect exact answers with that approach.

More precisely, to use integer arithmetic, you need the base to be an integer and the exponent to be a non-negative integer.

0
Hartmut Pfitzinger On

Since you are programming a calculator, speed is not your concern but the number of reliable digits is. So, you could try to use a double precision library. It uses 64-Bit-doubles but has only about 200 FLOPS at 16MHz CPU clock and much less at higher-order calculations like exp(), log(), or sin(). Thus, it will take a second after having typed in the digits and pressed the enter button but this was also the case with the old 8-Bit-based pocket caluclators.

See this Link (only in German)