amphibious:
...
Somehow this gives me 1, 2, 3, 7, 15..., 127...
SPI.transfer(outPut[i]);
but at some point in my work this array would have 200 numbers and it doesn't make much sense to me...
Thx
ff
The library function pow() operates on floating point arguments and returns a floating point value. It may turn out that 2.0 to the power 2.0 calculates out to be something slightly less than 4.0.
To round a positive floating point value to the nearest integer, add 0.5 first.
So it could go like this:
unsigned int outPut;
for (int i=0; i < 16; i++) {
outPut = pow(2, i)+0.5; // Round off floating point to nearest integer
Serial.print(outPut);
.
.
.
However... And This Is Important:
If you want integer powers of an integer, there is really no need to go through all of the floating point stuff. (I know, I know, the presence of a library function tries to protect you from actually thinking about what is going on, but the floating point stuff is horribly inefficient in terms of code size as well as run time).
A general positive-integer-to-positive-integer power function could look like this:
unsigned int Pow(unsigned int base, byte ex)
{
unsigned retval = 1;
for (unsigned i = 0; i < ex; i++) {
retval *= base;
}
return retval;
}
If you only need powers of 2, it's even simpler:
unsigned int Pow2(byte ex)
{
return 1 << ex;
}
So, to compare results, consider something like the following sketch:
void setup()
{
Serial.begin(9600);
}
void loop()
{
unsigned int outPut;
for (int i=0; i < 16; i++) {
outPut = pow(2, i) + 0.5; // Round off floating point to nearest integer
Serial.print(outPut);
Serial.print(" ");
outPut = Pow(2, i); // Integer raised to an integer power
Serial.print(outPut);
outPut = Pow2(i); // 2 raised to an integer power
Serial.print(" ");
Serial.println(outPut);
delay(100);
}
delay(10000);
}
// Integer power to integer function:
unsigned int Pow(unsigned int base, byte ex)
{
// Stuff I showed above
}
// Power of 2
unsigned int Pow2(byte ex)
{
// Stuff I showed above
}
Output:
1 1 1
2 2 2
4 4 4
8 8 8
16 16 16
32 32 32
64 64 64
128 128 128
256 256 256
512 512 512
1024 1024 1024
2048 2048 2048
4096 4096 4096
8192 8192 8192
16384 16384 16384
32768 32768 32768
Regards,
Dave
Footnote:
Even though we don't recommend the floating point function for simple integer powers, it's important to realize that whenever floating point operations are involved there is always the possibility of roundoff error. Converting floating point values to integer values always truncates the fractional part, so, for example a floating point number like 3.999999 becomes 3 if you just assign it to an integer variable. Rounding of positive values is easily performed by adding 1/2 before truncating.
And, by the way, case is important in identifiers: pow() is not the same as Pow(). Generally speaking, it is best to paste the actual code that you are asking about into your post.