• micka190@lemmy.world
    link
    fedilink
    English
    arrow-up
    2
    ·
    6 months ago

    In certain situations, it even disallows making assumptions about equality and ordering between floats.

    I’m guessing it does this when you define both floats in the same location with constant values.

    The correct way to compare floats whose values you don’t know ahead of time is to compare the absolute of their delta against a threshold.

    i.e.

    abs(a - b) <= 0.00001

    The idea being that you can’t really compare floats due to how they work. By subtracting them, you can make sure the values are “close enough” and avoid issues with precision not actually mattering all that much past the given threshold. If you define 2 constant values, though, the compiler can probably simplify it for you and just say “Yeah, these two should be the same value at runtime”.

    • Ephera
      link
      fedilink
      English
      arrow-up
      3
      ·
      6 months ago

      Unfortunately, that’s not what it’s about.

      With Rust’s language design¹, one could easily forbid ever comparing two floats via the normal operators (not just for literals), but they decided to allow that nonetheless. I’m guessing, because it would just be too annoying for generic implementations, if you’d always need special treatment for floats.

      Rather, what I was referring to, is that they’ve split partial ordering and partial equality from their total variants. And integers are marked that they can do total equality and total ordering, whereas floats are not.

      Honestly, it doesn’t come up a lot, but I know for example, if you want to use something as a key in a HashMap, it needs to have total equality.
      And in a BTreeMap (basically a binary tree, i.e. keys are inserted in a sorted manner), total ordering is required for the keys.

      ¹) Basically, comparison is typed and each type needs to opt into comparison with any type it wants to be compared to. So, if you define a new data type, then by default you cannot ask it whether it’s equal to or less/more than anything else.

    • Miaou@jlai.lu
      link
      fedilink
      English
      arrow-up
      1
      ·
      edit-2
      6 months ago

      Rust has a warning (has it been promoted to error? I think it was supposed to be) about comparing floats. Nothing to do with same being const. You basically don’t have an equality operator for them