The int
override rounds down. Since floating point operations are inaccurate, the calculation may be 3.999999...
Use round(x)
to get the correct result.
Since you always want to round down, you can use both floor
and (int)
-- but you run into the observed error as soon as the instability of floating point calculations results in a slightly less value -- something in the order of 10-15, for double
sized calculations. Use a tiny epsilon value to counteract that.
Note that the epsilon "fudge" value below will relate to the number of significant digits in your original number. For larger numbers, you need a smaller epsilon.
#include <stdio.h>
#include <string.h>
#include <math.h>
int main (void)
{
double x;
int z;
x=pow(64,(1.0/3));
printf("x=%lf\n",x);
printf("x=%.30lf\n",x);
z=(int)x;
printf("%d\n",z);
z=(int)(x+0.000000000000005);
printf("%d\n",z);
x=pow(64,(1.0/4));
printf("x=%lf\n",x);
printf("x=%.30lf\n",x);
z=(int)x;
printf("%d\n",z);
z=(int)(x+0.0000000000000005);
printf("%d\n",z);
return 1;
}
results, for powers of 1/3 and 1/4, in
x=4.000000
x=3.999999999999999555910790149937
3
4
x=2.828427
x=2.828427124746190290949243717478
2
2