[][src]Function nikisas::tan

pub fn tan(x: f32) -> f32

Computes tangent of a number.

Notes

The input domain is limited to approximately [-2.1e+9, 2.1e+9] due to implementation details. Near asymptotes (-π/2, π/2) the values get quite inaccurate.

Examples

use nikisas::{tan, consts::PI};
assert_eq!(tan(0.25 * PI), 1.0);

Implementation details

The input x is reduced to an integer k and real z such that

  x = k * π / 2 + z and |z| ≤ π / 4

This is the reason why the input domain is limited to smaller range, because the integral part must fit into 32-bit integer.

Then, the approximation is split into 2 pieces. Let's consider one period of the tangent from -π/2 to π/2:

  • for x in [-π/4, π/4], tan(x) = tan(z),
  • for x in [-π/2, -π/4) ∪ (π/4, π/2], tan(x) = -1 / tan(z).

To determine in which part of the period number x falls, i suffices to check if is even (first case) or odd (second case).

The tangent of z is approximated using a polynomial in the form:

  tan(z) ≈ z + z^3 * P(z^2)

The "prefix" corresponds to coefficients of low-degree Taylor polynomial of tan(z) for z = 0 and P is found using special minimax algorithm in Sollya. The use of z^2 instead of simply z is due to the fact that the tangent is an odd function (z^3 multiplier before P(z^2) is important).

There is also a special case when |z| is near π/4. Depending on the sign of z, the exact values of tan(z) are 1, respectively -1. We return them without employing any approximation.