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 )
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
andlog
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.