Skip to content

[Clang] No-zero result from a*a - b*b when a == b #163470

@zhqrbitee

Description

@zhqrbitee

Hi,
For below codes,

#include <iostream>
#include <cmath>

double test1(double a, double b) {
    return (a*a - b*b) ;
}


int main() {
    std::cout << "---------------------------------" << std::endl;
    std::cout << test1(1.1, 1.1) << std::endl;
    std::cout << "---------------------------------" << std::endl;
    return 0;
}

If a == b, then I would expect the test1 function return me exactly 0.0, as a * a should be exactly equal to b * b. However, it always return me a small value in my MacBook (with M2 chips).
I compared the assembly codes from latest clang and GCC with -O3 in compiler explorer (in arm64): both of them use fused multiply-add instructions, but the GCC one can produce 0.0 as expected, while the clang one produces 8.88178e-18.

Image

The compiler explorer link is: https://godbolt.org/z/93Tej6d66

I know floating-point issues can be subtle, but it seems returning 0.0 in this case makes more sense to me.

Metadata

Metadata

Assignees

No one assigned

    Labels

    floating-pointFloating-point mathquestionA question, not bug report. Check out https://llvm.org/docs/GettingInvolved.html instead!

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions