If I enter m=pow(2,4); I get the expected result of m=16.
If I enter int n = 4; m=pow(2,n); I get the unexpected result of 15. For different values of n, m is always 1 less than expected.
Actual code -
int n=4;
int m;
void setup()
{
Serial.begin(9600); //starts serial communication
}
void loop()
{
Serial.println(n);
m = pow(2, n);
Serial.println(m);
}
The compiler optimizes pow(2,4) away to the correct answer. When you use a variable it actually has to do the calc. It's working with float and so the answer you get is something like 15.999. When you put that into an int it gets truncated to 15.
Thanks WildBill.
After struggling with this for days, about an hour after posting I wondered about .999 type errors.
Changing to const int n=4; gave correct result of 16.
If n really was a variable then would the correct solution be to use a float for answer m, then round to nearest whole number?
It is better to use 222.... n times?
FYI, I have built a working "Tower of Hanoi" Meccano (Erector) robot.
Currently programmed just for 4 discs (2^n-1=15 moves), programmed longhand ie AtoB; AtoC; etc for 15 moves.
I intend to add a command "Enter no of Discs" then program will execute according to the number (button push) entered.
It is better to use 222.... n times?
In my opinion, yes. It will certainly be faster.
Thanks PaulS, but It wasn't a hypothetical question nor was it related to speed.
While I appreciate your input, in context, my question was, would 222.....n times eliminate the error caused by floating point maths and truncated results?
my question was, would 222.....n times eliminate the error caused by floating point maths and truncated results?
If it didn't solve the problem, I would not have endorsed it.