Pow function not working regular in another function.

Hi, i guess find a bug.

#include <math.h>

byte dtt;
void setup() {
Serial.begin(9600);
Serial.print("Normal= (2^3)=8=0b1000 = ");
dtt=4;
Serial.println(byte(pow(2,dtt-1)),BIN);
Serial.println("----------------In Func------------ ");
Serial.println();
yk(1,4);
}
void loop() {
}

void yk(byte fr,byte sc){
  Serial.print("Function parameter(sc) =   ");
  Serial.println(sc,BIN);
  Serial.println("Now,sc value is 4");
  Serial.println();
  byte hh= byte(pow(2,sc-1));
  Serial.println();
  Serial.println("the result must 2^(4-1)=2^3=8=0b1000");
  Serial.println();
  Serial.println("But in another function result = ");
  Serial.println();
  Serial.print(" byte(pow(2,sc-1)) =(hh)   ");
  Serial.println(hh,BIN);
  Serial.println();
  Serial.println("Yeah,Result is false");
  Serial.println("It must 8=0b1000 Not 7 not 0b111");
  Serial.println("Where is 1 ?");
}

Here’s a simplified sketch that demonstrates this issue:

byte globalExp = 3;

void setup() {
  Serial.begin(9600);
  byte localExp = 3;
  Serial.print("pow(2, localExp) = ");
  Serial.println(pow(2, localExp), 7);
  Serial.print("byte(pow(2, localExp)) = ");
  Serial.println(byte(pow(2, localExp)));
  Serial.print("pow(2, globalExp) = ");
  Serial.println(pow(2, globalExp), 7);
  Serial.print("byte(pow(2, globalExp)) = ");
  Serial.println(byte(pow(2, globalExp)));
}

void loop() {}

output:

pow(2, localExp) = 8.0000000
byte(pow(2, localExp)) = 8
pow(2, globalExp) = 7.9999980
byte(pow(2, globalExp)) = 7

The issue is caused by the non-exact nature of double. When you cast the return value to byte it is always rounded down, even if the result is 7.99999.

Hi, i guess find a bug.

Guess again. You are misusing the function. Using pow() to do bitshifting just will not work. Get over it.