The same operations seem to work differently for larger and smaller values (I think the code below explains the question better than I could in words) I have calculated max and max3 in the same way except the values are different. Similarly I have calculated max2 and max4 the exact same way with different values. Yet the answer I'm getting is very different?:
#include <stdio.h>
#include <math.h>
int main(void)
{
// 86997171 / 48 = 1812441.0625
int max = ceil((float) 86997171 / 48);
float max2 = ((float) 86997171)/ 48;
printf("max = %i, max2 = %f\n", max, max2);
int max3 = ceil((float) 3 / 2);
float max4 = ((float) 3) / 2;
printf("ma3 = %i, max4 = %f\n", max3, max4);
}
Output:
max = 1812441, max2 = 1812441.000000
ma3 = 2, max4 = 1.500000
I was expecting max = 1812442, max2 = 1812441.062500 to be the output, since that's what it should be in principle. Now I don't know what to do
CodePudding user response:
In C, float
is usually 4 bytes (on most compilers), so it's persicion is 6-9 significant digits, typically 7 digits.
Your number in question, 1812441.0625
has 11 digits.
You should used double
which in C is usually 8 bytes (on most compilers) so it's persicion is 15-18 significant digits, typically 16 digits, and therefore can keep the precision of your number.
In fact, using double
in this case gives:
max = 1812442, max2 = 1812441.062500
ma3 = 2, max4 = 1.500000
which is what you need.
Link.