0

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

MathiasDG
  • 81
  • 1
  • 9
  • In C (or C++), you'd call `nextafter` and subtract. Unfortunately there is no .NET wrapper for this useful operation. – Ben Voigt Oct 22 '15 at 13:57
  • 1
    Duplicate of http://stackoverflow.com/questions/9485943/calculate-the-unit-in-the-last-place-ulp-for-doubles – Pascal Cuoq Oct 22 '15 at 23:28

2 Answers2

1

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.
ergonaut
  • 6,929
  • 1
  • 17
  • 47
1

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, after x in the direction of y ... 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.

Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256