libm/math/atan2f.rs
1/* origin: FreeBSD /usr/src/lib/msun/src/e_atan2f.c */
2/*
3 * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
4 */
5/*
6 * ====================================================
7 * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
8 *
9 * Developed at SunPro, a Sun Microsystems, Inc. business.
10 * Permission to use, copy, modify, and distribute this
11 * software is freely granted, provided that this notice
12 * is preserved.
13 * ====================================================
14 */
15
16use super::{atanf, fabsf};
17
18const PI: f32 = 3.1415927410e+00; /* 0x40490fdb */
19const PI_LO: f32 = -8.7422776573e-08; /* 0xb3bbbd2e */
20
21/// Arctangent of y/x (f32)
22///
23/// Computes the inverse tangent (arc tangent) of `y/x`.
24/// Produces the correct result even for angles near pi/2 or -pi/2 (that is, when `x` is near 0).
25/// Returns a value in radians, in the range of -pi to pi.
26#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
27pub fn atan2f(y: f32, x: f32) -> f32 {
28 if x.is_nan() || y.is_nan() {
29 return x + y;
30 }
31 let mut ix = x.to_bits();
32 let mut iy = y.to_bits();
33
34 if ix == 0x3f800000 {
35 /* x=1.0 */
36 return atanf(y);
37 }
38 let m = ((iy >> 31) & 1) | ((ix >> 30) & 2); /* 2*sign(x)+sign(y) */
39 ix &= 0x7fffffff;
40 iy &= 0x7fffffff;
41
42 /* when y = 0 */
43 if iy == 0 {
44 return match m {
45 0 | 1 => y, /* atan(+-0,+anything)=+-0 */
46 2 => PI, /* atan(+0,-anything) = pi */
47 3 | _ => -PI, /* atan(-0,-anything) =-pi */
48 };
49 }
50 /* when x = 0 */
51 if ix == 0 {
52 return if m & 1 != 0 { -PI / 2. } else { PI / 2. };
53 }
54 /* when x is INF */
55 if ix == 0x7f800000 {
56 return if iy == 0x7f800000 {
57 match m {
58 0 => PI / 4., /* atan(+INF,+INF) */
59 1 => -PI / 4., /* atan(-INF,+INF) */
60 2 => 3. * PI / 4., /* atan(+INF,-INF)*/
61 3 | _ => -3. * PI / 4., /* atan(-INF,-INF)*/
62 }
63 } else {
64 match m {
65 0 => 0., /* atan(+...,+INF) */
66 1 => -0., /* atan(-...,+INF) */
67 2 => PI, /* atan(+...,-INF) */
68 3 | _ => -PI, /* atan(-...,-INF) */
69 }
70 };
71 }
72 /* |y/x| > 0x1p26 */
73 if (ix + (26 << 23) < iy) || (iy == 0x7f800000) {
74 return if m & 1 != 0 { -PI / 2. } else { PI / 2. };
75 }
76
77 /* z = atan(|y/x|) with correct underflow */
78 let z = if (m & 2 != 0) && (iy + (26 << 23) < ix) {
79 /*|y/x| < 0x1p-26, x < 0 */
80 0.
81 } else {
82 atanf(fabsf(y / x))
83 };
84 match m {
85 0 => z, /* atan(+,+) */
86 1 => -z, /* atan(-,+) */
87 2 => PI - (z - PI_LO), /* atan(+,-) */
88 _ => (z - PI_LO) - PI, /* case 3 */ /* atan(-,-) */
89 }
90}