1

I am having a temporary lapse of judgement, or not understanding how the power method works, but when I put 10 to the power of a number, it is that value -1. So:

10*10 = 100

Then I would assume, 10^2 = 100

So if I had a variable i, that was equal to 2, and I asked arduino for 10 to the power of i, I would expect it to do 10^2, and then give me 100, but instead I get 99. What am I missing?

void setup() {
Serial.begin(9600);
}
void loop() {
for (int i =0; i<5; i++){
 int power = i;
 Serial.print(power);
 Serial.print(":");
 int multiplier = pow(10,power);
 Serial.println(multiplier);
 }
}
Juraj
18.3k4 gold badges31 silver badges49 bronze badges
asked Nov 5, 2018 at 21:37
2
  • ^ is not power operator in C and C++. it is bitwise XOR Commented Nov 6, 2018 at 5:30
  • stackoverflow.com/questions/4843304/… Commented Nov 6, 2018 at 5:32

2 Answers 2

3

pow() works with floating point numbers.

Floating point numbers are just an approximation. You will very rarely get precise results using floating point numbers.

Instead you could write your own little integer-based ipow() function.

answered Nov 5, 2018 at 21:48
3

I put this code into the IDE, and for n>=2, I got 99, 999, 9999 etc. The catch is that Arduino uses floating point arithmetic to implement the pow() function, and some of your values are being truncated as ints. If you change:

 int multiplier = pow(10,power);

to

 float multiplier = pow(10,power);

The results should be as expected.

(The brief reason why floats are used is related to the fact that it is very easy to calculate the pow() function using logs, and this makes it easy to pow() non-integers too. This also means that it may not be as exact as you would hope).

answered Nov 5, 2018 at 21:52

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.