Pages: [1]   Go Down
Author Topic: Weird int, or pow behaviour...  (Read 1030 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 9
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Here is my problem:

Code:
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
« Last Edit: July 19, 2009, 06:20:55 pm by hmpws » Logged

London, England
Offline Offline
Edison Member
*
Karma: 4
Posts: 1026
Go! Go! Arduinoooo !!!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Dallas, Texas
Offline Offline
God Member
*****
Karma: 0
Posts: 861
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Global Moderator
Dallas
Offline Offline
Shannon Member
*****
Karma: 210
Posts: 13030
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

This...

Code:
pow(2,2)

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

Code:
Serial.println( 4.0 );

This...

Code:
pow(2,n)

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

Dallas, Texas
Offline Offline
God Member
*****
Karma: 0
Posts: 861
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Pages: [1]   Go Up
Jump to: