Go Down

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


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(){

void loop(){

Here are the print out:




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.


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


Code: [Select]

...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 );


Code: [Select]

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


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

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131