Assuming there's a float number with 7 digits how to find the smallest number that can be added to that float?
Example 1: 1234.567f + 0000.001f = 1234.568f
Example 2: 0.01234567 + 0.00000001f = 0.01234568f
Assuming there's a float number with 7 digits how to find the smallest number that can be added to that float?
Example 1: 1234.567f + 0000.001f = 1234.568f
Example 2: 0.01234567 + 0.00000001f = 0.01234568f
To find the smallest epsilon, you could start with 10eN where N is 1, and move down to a smaller number and add it. Then compare it to the original number.
number = x
N = 1
newnumber = 3
while (number <> newnumber){
newnumber = (number + 10eN)
N = N - 1
}
Then 10e(N+1) is the smallest epsilon.
OP added C#
after posting of this C
answer.
Will leave this C solution up as a reference.
Print the number out in exponential format and change each digit, to '0' or '1'
float smallest_float_summable(float f, int digs) {
char buf[20];
sprintf(buf, "%.*e", digs - 1, f);
char *p = buf;
while (*p != 'e') {
if (isdigit(*p)) {
*p = '0' + (p[1] == 'e');
}
p++;
}
float y;
sscanf(buf, "%e", &y);
return y;
}
printf("%e\n", smallest_float_summable(1234.567f, 7));
// 1.000000e-03
This will not get the smallest as the typically a number near 1/2 the value of smallest_float_summable()
will effect the change, yet this seems to match OP's intent.
To get the smallest number that will effect some change, simple use nextafter()
The
nextafter
functions determine the next representable value, in the type of the function, afterx
in the direction ofy
... C11dr §7.12.11.3 2
#include <math.h>
float smallest_change(float f) {
float dif = f - nextafterf(f, 0);
return dif;
}
[Edit]
@aka.nice correctly points out that even smaller, maybe about 1/2 dif
will effect a change. Will ponder this.