Outcome of power function changes after conversion to integer

Hi all,

First post of someone just starting with Arduino and C, so maybe bit of a newbie question:
I have a power function in my code that calculates 2 to the power of a variable (2^i). The outcome is a float. This part works fine. However, when I convert that float to a int for further use, it subtracts 1 from it in most cases (when i > 2). This is clear in my serial output:

2^0 = 1.00 which is rounded off to: 1
2^1 = 2.00 which is rounded off to: 2
2^2 = 4.00 which is rounded off to: 3
2^3 = 8.00 which is rounded off to: 7
2^4 = 16.00 which is rounded off to: 15
2^5 = 32.00 which is rounded off to: 31
2^6 = 64.00 which is rounded off to: 63
2^7 = 128.00 which is rounded off to: 127
2^8 = 256.00 which is rounded off to: 255

So from i >=3, the integer rounds the float off with a -1 operation, it seems. Anyone know why this is? Below is the code that generated this serial output.

float outcome = 0;
int outcomeRounded = 0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  for (int i=0; i<=8; i++)  {
  outcome = (pow(2, i));
  outcomeRounded = outcome;
  Serial.print("2^");
  Serial.print(i);
  Serial.print(" = ");
  Serial.print(outcome);
  Serial.print("  which is rounded off to: ");
  Serial.println(outcomeRounded);
  }
  delay(200000);
}

The pow function is a float function, not an int function. The result, when printed to two decimal places may look correct, but the value stored is just under the int that you want it to be.

2^3, using pow, is 7.9999999, which, when printed to to decimal places, is 8.00, but is in fact not quite 8.

The moral of the story is "Don't use pow to perform integer arithmetic."

the integer rounds the float off with a -1 operation

The problem is that it doesn't round. It just truncates.

Thanks for the quick replies!
Ah, so then 2^0 and 2^1 escape this issue because they are not 'proper' power functions?

Ah, so then 2^0 and 2^1 escape this issue because they are not 'proper' power functions?

No, it's just that they're less inaccurate.

If you want to generate integer powers of two, the left shift function is simpler and generally faster.
1<<0 = 1 = 20
1<<1 = 2 = 21
1<<2 = 4 = 22
1<<3 = 8 = 23

Thanks guys/gals!

To round use round().