Go Down

Topic: Weird int, or pow behaviour... (Read 1 time) previous topic - next topic

hmpws

Jul 20, 2009, 01:05 am Last Edit: Jul 20, 2009, 01:20 am by hmpws Reason: 1
Here is my problem:

Code: [Select]
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

Mike Mc

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.

EmilyJane

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.

Coding Badly

This...

Code: [Select]
pow(2,2)

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

Code: [Select]
Serial.println( 4.0 );

This...

Code: [Select]
pow(2,n)

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

EmilyJane

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

Go Up