Home > Software engineering >  Power function is returning different value in different text editor
Power function is returning different value in different text editor

Time:01-31

I am trying to use power function in a program but it is displaying/returning different values in different text editor. Below is the simple code. I have typecasted since power returns double. In code blocks text editor, the power function is returning 100. But in atom text editor, it is returning 99.But the same function in atom returns 100 if i replace count by 2. Am I missing installation of any extension in atom?. I don't know what is going on. Any suggestions/corrections are welcome.

#include <stdio.h>
#include <math.h>

 int main(){
  int count=2;
  printf("%d",(int)pow(10,count));
  return 0;
}

CodePudding user response:

My guess is that this is due to a floating point rounding error. It may be that, while the real answer is 100, pow(10, 2) is returning 99.99998. When you convert that to an int, the decimal part gets chopped off.

What you can do is, instead of casting right away, run the result through the lround function (also found in math.h). This will return a long.

CodePudding user response:

Avoid the pow function at all cost! It calculates a double raised with a double (for all possible values). This is an extremely complex calculation and it's done using an approximation. Rounding the result instead of using the default double to integer cast (which is defined as "round to zero") helps a bit, but not when the approximation errors more than 0.5.

If you intend to calculate "integer raised with an integer" I strongly suggest that you write your own that simply loops over the exponent -- it's way faster and it doesn't have any approximation problems.

(I say this as someone who has spent 25 years writing C compilers.)

  •  Tags:  
  • Related