Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I got different results with pow(10,2) and pow(10,j), j=2;

This one prints 100:

int j=2;
int i= pow(10,2);  
printf("%d\n", i);

and this one prints 99:

int j=2;
int i= pow(10,j);  
printf("%d\n", i);

Why?

like image 435
Rimgaudas Tumėnas Avatar asked Oct 01 '13 22:10

Rimgaudas Tumėnas


2 Answers

What's going on is that you have a C implementation whose standard library has a very low quality implementation of pow which is returning inexact results even when the exact result is representable in the type (double). The call to pow(10,2) seems to producing the value just below 100.0, which, when rounded to an integer, yields 99. The reason you don't see this when the arguments are constant is that the compiler took the liberty to optimize out the call alltogether and replace it with a constant 100 at compiletime.

If your intent is to do integer powers, don't use the pow function. Write a proper integer power function, or when the exponent is known, just write out the multiplication directly.

like image 100
R.. GitHub STOP HELPING ICE Avatar answered Nov 07 '22 18:11

R.. GitHub STOP HELPING ICE


In the first case, I suspect the compiler has optimized the value to 10*10 without actually calling pow (compilers do actually do this). In the second case, it looks like you have a floating-point rounding error. The result is almost 100 but not quite, and the implicit cast to int truncates it.

The pow function operates on double, not int.

In general (but not always), when you convert doubles to integers, you call round(). Eg:

int i = (int) round(pow(10,j));

If your C library doesn't have this, you can emulate:

#define round(x) floor((x)+0.5)
like image 2
paddy Avatar answered Nov 07 '22 17:11

paddy