News for hackers. Stuff that matters.
Re:Uncle Bob and Silver Bullets (2017) by marginalia_nu on Monday July 04, 2022 @12:33PM (#31978915)
Floats can be subnormal, and different bit patterns can represent the same value. It's not as easy as just comparing bits.

Here is some cursed C code to play with:

  #include <stdio.h>
  #include <float.h>
  #include <math.h>

  int main() {
    int a = 0x1000002;
    int b = 0x2000001;
    float* fa = (float*)&a;
    float* fb = (float*)&b;
    printf("value-equals? %d\n", *fa == *fb);
    printf("fabs-equals? %d\n", fabs(*fa-*fb)<FLT_EPSILON);
  }
May print something like

  value-equals? 0
  fabs-equals? 1
Re:Uncle Bob and Silver Bullets (2017) by eesmith on Monday July 04, 2022 @04:15PM (#31981302)
Could you explain why that output is cursed?

I get the same output using the following (I switched to the portable memcpy solution.)

  #include <stdio.h>
  #include <float.h>
  #include <math.h>

  int main() {
    int a = 0x361dc5df; // 2.351e-6f
    int b = 0x361e3e22; // 2.358e-6f;
    float fa, fb;
    memcpy(&fa, &a, 4);
    memcpy(&fb, &b, 4);
    printf("value-equals? %d\n", fa == fb);
    printf("fabs-equals? %d\n", fabs(fa-fb)<FLT_EPSILON);
  }
Since FLT_EPSILON is 1.19209290E-07F , I would expect a lot of small, close numbers to give the same output, even without touching subnormal values.
Re:Uncle Bob and Silver Bullets (2017) by jbay808 on Monday July 04, 2022 @12:48PM (#31979097)
I'm not sure how subnormal numbers are relevant. For binary floats, the only duplicate values are (+0, -0) and the NaNs, and in both of those cases it's really up to you to decide if those are really representing the same value or not.
Re:Uncle Bob and Silver Bullets (2017) by marginalia_nu on Monday July 04, 2022 @12:50PM (#31979122)
I'm arguing against the notion that floats are just bit patterns in memory. If you base your operator== on such a notion, you will get very weird behavior.