Problem with POW() function

I think there is an error with POW() function. Here is my code:

void setup()
{
Serial.begin(9600);
}
void loop()
{
if (Serial.available()>0)
Serial.println(pow(10.0,Serial.read()-0x30), DEC);
}

It is a simple code that take an input from serial terminal and calculate 10^(input number). I ran simple test numbers and here are the results:

input 0 => 1
input 1 => 10
input 2 => 99
input 3 => 999
input 4 => 9999
input 5 => 100000

Why 10^2, 10^3, and 10^4 gave me a wrong answer? Is that a bug in the POW() function or something wrong with my code? Help please!

Why 10^2, 10^3, and 10^4 gave me a wrong answer? Is that a bug in the POW() function or something wrong with my code? Help please!

My guess would be the error is due to the use of a floating point number for the base.

--Phil.

Yea, pow() operates on floating point numbers, so they're not always exactly correct - then, when they get converted to integers, they're truncated, not rounded, so you may be off by 1. You could try adding 0.1 or 0.001 or something to the result, that might help.

when they get converted to integers, they're truncated, not rounded, so you may be off by 1. You could try adding 0.1 or 0.001 or something to the result

To get rounding instead of truncation, adding 0.5 is what you want, no?

-j

I'm seeing issues with pow() as well that are not just integer/float conversion problems:

In <math.h>, the prototype for pow() has it taking and returning doubles:

  /**
     \ingroup avr_math

     The function pow() returns the value of \c x to the exponent \c y.
  */
extern double pow(double __x, double __y) __ATTR_CONST__;

I'm using it something like this:

double f1 = 4833333.0;
double f2 = pow(2.0L, (double)f1);

The result I'm getting is 10.056141, when it should be returning something like 28.508759 (according to oocalc).

Carl

Are you overflowing? 24833333 is a big number, even for a float.

Looks like it's time to check the ATmega8/168 datasheet and see what the largest float you can hold is.

-j

Are you overflowing? 24833333 is a big number, even for a float.

Looks like it's time to check the ATmega8/168 datasheet and see what the largest float you can hold is.

-j

Doh! Sorry, that's what my debugging code showed (x 1000000). It was actually 24.833333

Can you post your whole sketch, cdunham?

Can you post your whole sketch, cdunham?

I definitely could, but this is part of an in-progress library whose use requires sketches be built using a Makefile, etc.

I'll create a small test sketch that demonstrates this and post it later this evening.

Well, it looks like this is just a case of a difference between what the UI generates, and what the Makefile generates. Still more to figure out there, but the same sketch built with make is larger, and has the above behavior, while the one compiled and loaded through the UI works fine.

Sorry for falsely accusing pow() of falling down on the job...