Reputation: 3578
When I use the pow()
function, sometimes the results are off by one. For example, this code produces 124, but I know that 5³ should be 125.
#include<stdio.h>
#include<math.h>
int main(){
int i = pow(5, 3);
printf("%d", i);
}
Why is the result wrong?
Upvotes: -2
Views: 4801
Reputation: 234635
pow(x, y)
is likely implemented as exp(y * log(x))
: modern CPUs can evaluate exp
and log
in a couple of flicks of the wrist.
Although adequate for many scientific applications, when truncating the result to an integer, the result can be off for even trivial arguments. That's what is happening here.
Your best bet is to roll your own version of pow
for integer arguments; i.e. find one from a good library. As a starting point, see The most efficient way to implement an integer based power function pow(int, int)
Upvotes: 4
Reputation: 133
Use Float Data Type
#include <stdio.h>
#include <math.h>
int main()
{
float x=2;
float y=2;
float p= pow(x,y);
printf("%f",p);
return 0;
}
Upvotes: 2
Reputation: 51835
Your problem is that you are mixing integer variables with floating point math. My bet is that the result of 5^3
is something like 124.999999
due to rounding problems and when cast into integer variable get floor
ed to 124
.
There are 3 ways to deal with this:
more safely mix floating math and integers
int x=5,y=3,z;
z=floor(pow(x,y)+0.5);
// or
z=round(pow(x,y));
but using this will always present a possible risk of rounding errors affecting the result especially for higher exponents.
compute on floating variables only
so replace int
with float
or double
. This is a bit safer than #1 but still in some cases is this not usable (depends on the task). and may need occasional floor,ceil,round
along the way to get the wanted result correctly.
Use integer math only
This is the safest way (unless you cross the int
limit). The pow
can be computed on integer math relatively easily see:
Upvotes: 9
Reputation: 6206
You can use this function instead of pow
:
long long int Pow(long long int base, unsigned int exp)
{
if (exp > 0)
return base * Pow(base, exp-1);
return 1;
}
Upvotes: -4