user3810155
user3810155

Reputation:

Can the standard math functions handle infinity correctly?

int main() {
    double inf = INFINITY;
    double pi = acos(-1.0);
    printf("[1]: %f %f\n", atan(inf) / pi, atan(-inf) / pi);
    printf("[2]: %f %f\n", tan(inf) / pi, tan(-inf) / pi);
    return 0;
}

outputs

[1]: 0.500000 -0.500000
[2]: -nan -nan

Is such behaviour defined by the standard? Is [2] undefined behaviour? unspecified?

I want to be sure at least [1] is a guaranteed result.

Upvotes: 4

Views: 1293

Answers (1)

bashrc
bashrc

Reputation: 4835

Both are well defined behaviour. Quoting from http://en.cppreference.com

  • tan

    If the argument is ±0, it is returned unmodified.
    If the argument is ±∞, NaN is returned and FE_INVALID is raised.
    If the argument is NaN, NaN is returned.

  • atan

    If the argument is ±0, it is returned unmodified.
    If the argument is +∞, +π/2 is returned.
    If the argument is -∞, -π/2 is returned.
    If the argument is NaN, NaN is returned.

Upvotes: 5

Related Questions