1

I am having a temporary lapse of judgement, or not understanding how the power method works, but when I put 10 to the power of a number, it is that value -1. So:

10*10 = 100

Then I would assume, 10^2 = 100

So if I had a variable i, that was equal to 2, and I asked arduino for 10 to the power of i, I would expect it to do 10^2, and then give me 100, but instead I get 99. What am I missing?

void setup() {
Serial.begin(9600);
}

void loop() {
for (int i =0; i<5; i++){
   int power = i;
   Serial.print(power);
   Serial.print(":");

   int multiplier = pow(10,power);
   Serial.println(multiplier);

  }

}
4

I put this code into the IDE, and for n>=2, I got 99, 999, 9999 etc. The catch is that Arduino uses floating point arithmetic to implement the pow() function, and some of your values are being truncated as ints. If you change:

   int multiplier = pow(10,power);

to

   float multiplier = pow(10,power);

The results should be as expected.

(The brief reason why floats are used is related to the fact that it is very easy to calculate the pow() function using logs, and this makes it easy to pow() non-integers too. This also means that it may not be as exact as you would hope).

3

pow() works with floating point numbers.

Floating point numbers are just an approximation. You will very rarely get precise results using floating point numbers.

Instead you could write your own little integer-based ipow() function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.