 # pow(base, exponent) giving the wrong values...

I kept running into some odd behavior with something I was writing, and figured out that the pow() function wasn’t returning what I expected it to. So I just wrote a simple test program…

``````  int value = 0;
for (int a = 0; a <= 7; a++) {
value = pow (2, a);
Serial.print(a);
Serial.print(": ");
Serial.println(value);

}
``````

I expect this to return:
0: 1
1: 2
2: 4
3: 8
4: 16
5: 32
6: 64
7: 128

but it returns:
0: 1
1: 1
2: 3
3: 7
4: 15
5: 31
6: 63
7: 127

Am I doing something stupidly wrong here?

Even stranger is if I do 2^a… I get:

0: 2
1: 3
2: 0
3: 1
4: 6
5: 7
6: 4
7: 5

What’s going on here?

Mike

well, pow() is a floating point function, so you’re probably getting something like 1.99999, which of course is truncated to 1 when assigned to an integer value. Do

``````  value = 0.5 + pow(2,a);
``````

to get properly rounded integer values.
Meanwhile, in C, “^” is the XOR operator, not exponentiation. C doesn’t have any exponentiation operator. See Question 14.7

I wrote my own little int power(int, int) function (since I just need to deal with integers), and it works fine. Still really strange that pow() isn’t returning the right value, but at least my stuff works right now.

Thanks for that… and thanks for the correction about the XOR operator.

Mike

well, pow() is a floating point function, so you’re probably getting something like 1.99999, which of course is truncated to 1 when assigned to an integer value. Do

``````  value = 0.5 + pow(2,a);
``````

to get properly rounded integer values.
Meanwhile, in C, “^” is the XOR operator, not exponentiation. C doesn’t have any exponentiation operator. See Question 14.7