Go Down

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

hmpws

Jul 20, 2009, 01:05 amLast 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 problemvoid 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

#1
Jul 20, 2009, 12:30 pm
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

#2
Jul 20, 2009, 06:01 pm
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.

#3
Jul 21, 2009, 04:21 am
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

#4
Jul 21, 2009, 04:28 am
Ahh, good point, I hadn't thought of that.

Go Up

Please enter a valid email to subscribe