C and C++ atan and atan2 function instance usage

  • 2020-07-21 09:39:24
  • OfStack

In C language, math. h or cmath in C++, there are two arctangent functions, atan(double x) and atan2(double y,double x), which return the value of radians to be converted into angles and then processed by themselves.

The former accepts one tangent (the slope of the line) to get an Angle, but because of the regularity of the tangent, which could have two angles, it only returns one, because atan's range is from -90 to 90, which means it only deals with the 14 quadrant, so 1 doesn't use it.

The second atan2(double y,double x), where y represents the Y coordinate of a known point, and the return value is the Angle between this point and the far point and the positive direction of the x axis, so that it can handle any case of the four quadrants, and its corresponding range is -180~180

Such as:

Example 1: The Angle between a line with a slope of 1

[

cout < < * 180 / PI atan (1.0); / / 45 °

cout < < atan2 (1.0, 1.0) * 180 / PI; //45 degree quadrant 1

cout < < atan2 (1.0, 1.0) * 180 / PI; // the third quadrant of -135 degrees

]

The last two slopes are both 1 but atan can only solve for 1 45 degrees

Example 2: The Angle of a line with a slope of -1

[

cout < < atan (1.0) * 180 / PI; / / to 45 °

cout < < atan2 (1.0, 1.0) * 180 / PI; //-45° y is negative in the fourth quadrant

cout < < atan2 (1.0, 1.0) * 180 / PI; //135° x is negative in the second quadrant

]

What you usually do is not find the Angle of a line crossing the origin but the Angle of a line segment and this is especially useful for atan2

For example, find the Angle between the line segment AB (1.0,1.0) B(3.0,3.0) and the positive direction of the x axis

atan2 is expressed as atan2(y2-y1,x2-x1), namely atan2(3.0-1.0,3.0-1.0)

The idea is to shift the A point to the origin so that the B point becomes B' (x2-x1,y2-y1) and then go back to the previous point

Example 3:

[

A(0.0,5.0) B(5.0,10.0)

The included Angle of line segment AB is

cout < < atan2 (5.0, 5.0) * 180 / PI; / / 45 °

]

Above is this site to organize the relevant content, I hope to help you.


Related articles: