Consider large integer values
(float)input is a problem when int input is so large that converting to a float is inexact.
float commonly has 24 significant binary digits and large ints may not convert exactly to a float with the same value - instead the float is a rounded value.
int main(void) {
int i = (1 << 24) * 2 + 2;
for (int j = 0; j < 10; j++) {
float f = (float) i;
printf("i:0x%X %d, f:%.9g\n", (unsigned) i, i, f);
i++;
}
}
Ouptut
i:0x2000002 33554434, f:33554432
i:0x2000003 33554435, f:33554436
i:0x2000004 33554436, f:33554436 exact
i:0x2000005 33554437, f:33554436
i:0x2000006 33554438, f:33554440
i:0x2000007 33554439, f:33554440
i:0x2000008 33554440, f:33554440 exact
i:0x2000009 33554441, f:33554440
i:0x200000A 33554442, f:33554440
i:0x200000B 33554443, f:33554444
With the goal of largest float smaller than input integer:
the largest float smaller than input integer 33554435 is 33554432.0
the largest float smaller than input integer 33554437 is 33554436.0
Since 33554435, 33554436, 33554437 all convert to the same float, (float)input alone is insufficient to determine the correct answer.
I would expect additional code to cope with rounding issues.
Perhaps like:
float less_than_int(int i) {
float f = (float) i;
int j = (int) f;
if (j < i) {
return f;
}
// https://stackoverflow.com/a/79663556/2410359
return BitDecrement(f);
}
nextafter? I suspect that's the right way to do it: (1) Convert your int to a float f1. (2) If f1 is less than your integer, you already have your answer. (3) Use 'nextafter' to compute the next-smallest float f2. (4) Double-check that f2 is less than your integer. (5) It's your answer. (It will be a little bit tricky to do the tests in (2) and (4): you need to make sure to convert f1/f2 back to integer and compare the integers, not convert the int to float again and compare the floats.)Mathf.RoundToIntinstead, 0 and N-1 will only get results that are 0.5 or less, N-1 getting same amount of results, and the "middle" ints getting double as much results,. as they get rounded from range of their value plus -0.5 to + 0.5. Correct me if I'm wrong here please!