Skip to content

atan2 returns nan when the second argument is zero and data type is float with -ffast-math #1231

@Sauron-1

Description

@Sauron-1

When using xsimd::atan2 with float types and the -ffast-math compiler flag, the result for x=0.0 is NaN. Under standard math flags or with std::atan2, the result is correctly 1.570796.

To reproduce the bug:

#include <xsimd/xsimd.hpp>
#include <cstdio>

template<typename T>
[[gnu::noinline]] float xsimd_atan2(T v1, T v2) {
    using batch = xsimd::batch<T>;
    batch a = v1;
    batch b = v2;
    auto c = xsimd::atan2(a, b);
    return c.get(0);
}

int main() {
    float a = 1, b = 0;
    printf("xsimd::atan(%.1f, %.1f) = %f\nstd::atan(%.1f, %.1f) = %f\n",
            a, b, xsimd_atan2(a, b),
            a, b, std::atan2(a, b));
}

When compiled with -ffast-math, the output is:

xsimd::atan(1.0, 0.0) = -nan
std::atan(1.0, 0.0) = 1.570796

Both the master branch and v14.0.0 yield this result.
Tested compilers and compiler flags that reproduce the error:

  • g++: 15.2.0 and 12.5.0, with -ffast-math
  • clang++: 18-20, with -ffast-math -O1

Intel 2025.2.1 prints the correct result without the error.
Testing platform: Ubuntu 25.10 on AMD EPYC 9354.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions