About pow()

Hello everyone,

I have a question. I have no problem using pow command. Z = pow(x,y) Syntax pow(base, exponent).

But I’m having a problem here. Command is not working correctly

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}

void loop() {

int abc;
int us;

for ( abc = 1; abc<11;abc++)
{
us = pow(abc,3);
Serial.print(abc);
Serial.print(" base: ");
Serial.println(us);
}
while(1);
}

Thank you

"Command is not working correctly" is not helpful. What does the program do for you? What did you expect the program to do?

By the way, you are mixing floats and ints. ints tend to confuse beginners (who do not expect 1/2 to be zero) and mixing with floats can be even further confusing.

i get the following results on an uno

1 base: 1
2 base: 7
3 base: 26
4 base: 63
5 base: 124
6 base: 215
7 base: 342
8 base: 511
9 base: 728
10 base: 999

but these values on my laptop

     1       1
      2       8
      3      27
      4      64
      5     125
      6     216
      7     343
      8     512
      9     729
     10    1000

may just be a rounding error

If you make 'us' a float and display 6 decimal place you can see what is going wrong when you truncate the values:

1 base: 1.000000
2 base: 7.999998
3 base: 26.999994
4 base: 63.999977
5 base: 124.999977
6 base: 215.999954
7 base: 342.999786
8 base: 511.999633
9 base: 728.999633
10 base: 999.999816

Sort of a rounding error. When there is a difference, it is only by one. The function pow(...) returns a double which shares many of the characteristics of a float and IS a float on many Arduinos, but you only print ints. The double 7.99999 (if it even exists) looks like 8 to you and me but gets truncated to 7 when converted to an int. Do this:

int_variable = double_variable + 0.5 ;

if you want better rounding.

By the way, the program on the PC doesn't print "base:" so I wonder what was in THAT program.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.