C atan2() Function

The atan2() function computes the principal value of the arc tangent of the quotient of two values, returning an angle in radians. It takes into account the signs of the inputs to determine the correct quadrant for the resulting angle, ensuring a result within the interval [-π, +π].


Syntax of atan2()

</>
Copy
double atan2(double y, double x);

Parameters

ParameterDescription
yRepresents the proportion of the y-coordinate.
xRepresents the proportion of the x-coordinate. A domain error occurs if both arguments are zero.

Return Value

The function returns the principal arc tangent of the quotient, expressed in radians within the interval [-π, +π].

Note: This function automatically determines the appropriate quadrant for the angle by considering the signs of its inputs. In C++, it is also overloaded in <valarray>.


Examples for atan2()

Example 1: Calculating the Angle for a Point in the First Quadrant

This example demonstrates how to calculate the angle for a point that lies in the first quadrant using atan2().

Program

</>
Copy
#include <stdio.h>
#include <math.h>

int main() {
    double y = 5.0;
    double x = 5.0;
    double angle = atan2(y, x);
    printf("Angle in radians: %f\n", angle);
    return 0;
}

Explanation:

  1. Values for a point in the first quadrant are defined.
  2. The atan2() function computes the angle corresponding to the point (5.0, 5.0).
  3. The resulting angle is printed in radians.

Program Output:

Angle in radians: 0.785398

Example 2: Determining the Angle for a Point in the Second Quadrant

This example shows how to use atan2() to compute the angle for a point located in the second quadrant, where the x-coordinate is negative.

Program

</>
Copy
#include <stdio.h>
#include <math.h>

int main() {
    double y = 5.0;
    double x = -5.0;
    double angle = atan2(y, x);
    printf("Angle in radians: %f\n", angle);
    return 0;
}

Explanation:

  1. A point in the second quadrant is defined with a positive y-coordinate and a negative x-coordinate.
  2. The atan2() function calculates the angle, taking into account the sign of the x-coordinate.
  3. The computed angle is printed in radians.

Program Output:

Angle in radians: 2.356194

Example 3: Handling Negative Coordinates for a Point in the Fourth Quadrant

This example demonstrates how atan2() computes the angle for a point in the fourth quadrant where the y-coordinate is negative.

Program

</>
Copy
#include <stdio.h>
#include <math.h>

int main() {
    double y = -5.0;
    double x = 5.0;
    double angle = atan2(y, x);
    printf("Angle in radians: %f\n", angle);
    return 0;
}

Explanation:

  1. A point with a negative y-coordinate and a positive x-coordinate is defined, placing it in the fourth quadrant.
  2. The atan2() function computes the angle, adjusting for the negative y value.
  3. The calculated angle is printed in radians.

Program Output:

Angle in radians: -0.785398