0

Is it the case that, for any floats a and b, a + b will always == b + a?

mako
  • 1,201
  • 14
  • 30
  • 14
    Make up your mind which language you're asking this for. – Tibrogargan Jan 06 '23 at 19:24
  • 1
    For most modern situations, this is more about how the underlying machine handles floating point operations. That said, here in 2023 I would be very surprised by a situation in which commutativity didn't hold for addition. – Pointy Jan 06 '23 at 19:27
  • @Tibrogargan no. All of these languages support a standard set of behaviors, and if the standards differ greatly, I don't already know that. Additionally, the code I'm writing may need to be ported. – mako Jan 06 '23 at 19:33
  • @Pointy have a look at the duplicate – Richard Critten Jan 06 '23 at 20:02
  • @RichardCritten yea I would believe that C++ would be pretty cautious in its spec, but I'd still be (casually) interested to see a case where commutative addition didn't work – Pointy Jan 06 '23 at 20:15
  • @Pointy I loved the part where `a+b == a+b` is not guaranteed. – Richard Critten Jan 06 '23 at 20:22
  • 1
    It probably has to do with the Intel architecture, where the internal floating point registers are 80 bits, but saved-to-memory doubles are 64 bits. (I'm only guessing that the architecture is still like that; it was when I worked at Intel in 1983 lol) – Pointy Jan 06 '23 at 20:31
  • The real question I have is: where do you need this property? The results should be reasonably close enough, and you should never `==` compare two floats. Unit test suites, for example, usually have a `test_values_close` function or similar for float sanity checking. – Finomnis Jan 06 '23 at 23:44
  • Yeah, @Finomnis I don't think I do need it here at all, I rearranged some stuff and I'm not really even using == any more. I'm using the contrary < case (though this could have overlapping issues). It's a situation where I need to see if a distance has changed, if so, distances beyond that need to be recomputed. I was asking to find out whether I need to write a standard about which order the addition should happen in, if the answer was "yes, it's not commutative", I could have just maintained that order and things would have been fine. – mako Jan 07 '23 at 01:30

0 Answers0