Weird int, or pow behaviour...

Here is my problem:

int n = 2; // int = 3 etc. also has same problem
void setup(){
  Serial.begin(9600);
  Serial.println(pow(2,n));
  Serial.println((int)pow(2,n));
  Serial.println(pow(2,2));
  Serial.println((int)pow(2,2));
}

void loop(){
}

Here are the print out: 4.00

3

4.00

4

Hmm... what happened???

*NB: Tested with 0014, 0015 and 0016 on win *I have tested this further if I use ceil(pow(2,n)) or round then int it, it works properly... but not with floor (goes to 3)... so I suspect there is something there

I think POW is converting it to a float before operating on it, hence the digits after the decimal point. Using (int) is casting it back to an integer.

Yeah, and I'll bet if you could print the intermediate results to more precision you'd see that it's 3.999... instead of 4.00 and that is getting truncated to 3 when cast back to an integer. Floating point arithmetic is not exact.

This…

pow(2,2)

…is evaluated at compile-time (presumably using the Intel math coprocessor). Essentially, this is what’s output by the compiler…

Serial.println( 4.0 );

This…

pow(2,n)

…is executed by the Arduino (by the floating-point emulation library) with the resulting inaccuracy.

Ahh, good point, I hadn't thought of that.