Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-std

Source of release 0.7.4

0.7.4 / src / math / module.lucb

#==============================================================================================
#
#   math - The mathematical functions of the standard library
#
#   DESCRIPTION:
#       `import math` for `math.sqrt(x)`, `from math import sqrt` for `sqrt(x)` (§16.6). The
#       elementary functions (exp, log, pow, the trigonometric and hyperbolic functions, cbrt
#       and hypot) are written here in Base, so their results are the same bits on every
#       target and within about half an ulp; the files of this directory hold them, one family
#       each. The exactly specified operations (rounding, sqrt, fma, fmod, remainder and the
#       decompositions) are the C library's, which every target computes alike; the integer
#       functions are Base.
#
#==============================================================================================
from math_tables import asin_coefficients, atan_table_high, atan_table_low, exp_table_high, exp_table_low, inverse_ln2_128, inverse_step, ln2_128_high, ln2_128_low, ln2_double_high, ln2_double_low, ln2_high, ln2_low, log10_e_high, log10_e_low, log2_e_high, log2_e_low, log_inverse, log_point, log_table_high, log_table_low, pi_high, pi_low, pio2_1, pio2_2, pio2_3, pio2_4, pio2_high, pio2_low, sine_table, step_1, step_2, step_3, two_over_pi, two_over_pi_double
extern func c_floor as "floor"(x: f64) -> f64
extern func c_ceil as "ceil"(x: f64) -> f64
extern func c_round as "round"(x: f64) -> f64
extern func c_trunc as "trunc"(x: f64) -> f64
extern func c_sqrt as "sqrt"(x: f64) -> f64
extern func c_fmod as "fmod"(x: f64, y: f64) -> f64
extern func c_fma as "fma"(x: f64, y: f64, z: f64) -> f64
extern func c_fabs as "fabs"(x: f64) -> f64
extern func c_nextafter as "nextafter"(x: f64, toward: f64) -> f64
extern func c_frexp as "frexp"(x: f64, out exponent: i32) -> f64
extern func c_scalbn as "scalbn"(x: f64, exponent: i32) -> f64
extern func c_modf as "modf"(x: f64, out integral: f64) -> f64
extern func c_remainder as "remainder"(x: f64, y: f64) -> f64
## The ratio of a circle's circumference to its diameter.
pub let pi: f64 = 3.141592653589793
## A full turn in radians, two pi.
pub let tau: f64 = 6.283185307179586
## Euler's number.
pub let e: f64 = 2.718281828459045
## Built from bits so that no constant expression needs to overflow.
pub let infinity: f64 = f64.bits(9218868437227405312)
## A quiet not-a-number; unequal to everything, itself included.
pub let nan: f64 = f64.bits(9221120237041090560)

let sign_mask: u64 = 0x8000000000000000
let magnitude_mask: u64 = 0x7fffffffffffffff
let exponent_mask: u64 = 0x7ff0000000000000

# mark: Real functions ========================================================================

## Rounding: `floor` toward negative infinity, `ceil` toward positive, `round` to the
## nearest with halves away from zero, `trunc` toward zero.
pub func floor(x: f64) -> f64:
    return c_floor(x)

## The smallest integer value not less than `x`.
pub func ceil(x: f64) -> f64:
    return c_ceil(x)

## `x` rounded to the nearest integer, halves away from zero.
pub func round(x: f64) -> f64:
    return c_round(x)

## `x` with its fractional part removed, toward zero.
pub func trunc(x: f64) -> f64:
    return c_trunc(x)

## The square root of `x`.
pub func sqrt(x: f64) -> f64:
    return c_sqrt(x)

## The cube root of `x`.
pub func cbrt(x: f64) -> f64:
    return cbrt_value(x)

## `sqrt(x * x + y * y)` without overflow in the squares.
pub func hypot(x: f64, y: f64) -> f64:
    return hypot_value(x, y)

## The remainder of `x / y` with the sign of `x`, as C's `fmod`; a zero has the sign of `x`.
pub func mod(x: f64, y: f64) -> f64:
    let result = c_fmod(x, y)
    # MinGW's fmod loses the dividend's zero sign under directed rounding, as some
    # hosts' remainder does: restore it by bits, leaving a nonzero or NaN result.
    return copysign(result, x) if (result.bits() & magnitude_mask) == 0 else result

## `x` raised to the power `y`.
pub func pow(x: f64, y: f64) -> f64:
    return pow_value(x, y)

## `e` raised to the power `x`.
pub func exp(x: f64) -> f64:
    return exp_value(x)

## `2` raised to the power `x`.
pub func exp2(x: f64) -> f64:
    return exp2_value(x)

## The natural logarithm of `x`.
pub func log(x: f64) -> f64:
    return log_value(x)

## The base-2 logarithm of `x`.
pub func log2(x: f64) -> f64:
    return log2_value(x)

## The base-10 logarithm of `x`.
pub func log10(x: f64) -> f64:
    return log10_value(x)

## Natural logarithm of `1 + x`, retaining accuracy when adding `x` to one would
## round it away. At -1 the result is negative infinity; below -1 it is NaN.
pub func log1p(x: f64) -> f64:
    return log1p_value(x)

## `exp(x) - 1` without cancellation near zero. Signed zero is preserved.
pub func expm1(x: f64) -> f64:
    return expm1_value(x)

## Multiply `x * y` and add `z` with one final rounding, rather than rounding the
## product first. Uses the host's floating-point rounding mode.
pub func fma(x: f64, y: f64, z: f64) -> f64:
    return c_fma(x, y, z)

## The adjacent representable value toward `toward`; equal arguments return
## `toward`, including its zero sign. A NaN argument produces NaN.
pub func nextafter(x: f64, toward: f64) -> f64:
    return c_nextafter(x, toward)

## The adjacent representable value toward positive infinity. Positive infinity
## stays infinite; either zero becomes the smallest positive subnormal.
pub func next_up(x: f64) -> f64:
    return c_nextafter(x, infinity)

## The adjacent representable value toward negative infinity. Negative infinity
## stays infinite; either zero becomes the smallest negative subnormal.
pub func next_down(x: f64) -> f64:
    return c_nextafter(x, copysign(infinity, -1.0))

## Split `x` into `(fraction, exponent)` such that `x = fraction * 2**exponent`.
## A finite nonzero fraction has magnitude in [0.5, 1). Zero, infinity and NaN
## are returned unchanged with exponent zero, avoiding an unspecified C exponent.
pub func frexp(x: f64) -> (f64, i32):
    if x == 0.0 or not is_finite(x):
        return (x, 0)
    return c_frexp(x)

## Scale by an integer power of two, without forming that power as an intermediate
## float. Overflow/underflow follow the host rounding mode; signed zero survives.
pub func scalbn(x: f64, exponent: i32) -> f64:
    return c_scalbn(x, exponent)

## `(fractional, integral)` parts, both with the sign of `x`; the integral part
## truncates toward zero. Infinity has a signed-zero fraction; NaN gives two NaNs.
pub func modf(x: f64) -> (f64, f64):
    return c_modf(x)

## `x - n*y` for the nearest integer `n` to `x/y`, with ties choosing even `n`.
## This differs from `mod`, which truncates the quotient. Zero has the sign of `x`;
## a zero divisor or infinite dividend produces NaN.
pub func remainder(x: f64, y: f64) -> f64:
    let result = c_remainder(x, y)
    # Some host implementations lose the dividend's zero sign under directed
    # rounding. Restore it by bits without changing a nonzero or NaN result.
    return copysign(result, x) if (result.bits() & magnitude_mask) == 0 else result

## The sine of `x` radians.
pub func sin(x: f64) -> f64:
    return sin_value(x)

## The cosine of `x` radians.
pub func cos(x: f64) -> f64:
    return cos_value(x)

## The sine and the cosine of `x` radians, `(sin(x), cos(x))`, for about the price of one.
pub func sincos(x: f64) -> (f64, f64):
    return sincos_value(x)

## The tangent of `x` radians.
pub func tan(x: f64) -> f64:
    return tan_value(x)

## The arcsine of `x`, in radians.
pub func asin(x: f64) -> f64:
    return asin_value(x)

## The arccosine of `x`, in radians.
pub func acos(x: f64) -> f64:
    return acos_value(x)

## The arctangent of `x`, in radians.
pub func atan(x: f64) -> f64:
    return atan_value(x)

## The angle of the point `(x, y)`, in all four quadrants.
pub func atan2(y: f64, x: f64) -> f64:
    return atan2_value(y, x)

## The hyperbolic sine of `x`.
pub func sinh(x: f64) -> f64:
    return sinh_value(x)

## The hyperbolic cosine of `x`.
pub func cosh(x: f64) -> f64:
    return cosh_value(x)

## The hyperbolic tangent of `x`.
pub func tanh(x: f64) -> f64:
    return tanh_value(x)

# erf and erfc follow the method of Sun's fdlibm (s_erf.c, as in FreeBSD's msun), written
# anew in Base: a rational approximation in x² below 0.84375, one in |x| - 1 up to 1.25,
# and above that erfc(x) = exp(-x² - 0.5625 + R(1/x²)/S(1/x²)) / x with two rational fits
# split at 1/0.35. The coefficients are fdlibm's. Results are within two units in the last
# place (tests/math_accuracy holds the evidence); the exp they use is exp.lucb's.

## erf(1) in 24 bits, which the middle interval adds to; being short, `erx + P/Q` and
## `1 - erx - P/Q` round once.
let erx: f64 = 8.45062911510467529297e-01
## 2/sqrt(pi) - 1, the slope of erf at zero beyond x.
let efx: f64 = 1.28379167095512586316e-01

## erf(x) = x + x·P(x²)/Q(x²) on [0, 0.84375).
func erf_small(x: f64) -> f64:
    let z = x * x
    let p = 1.28379167095512558561e-01 + z * (-3.25042107247001499370e-01 + z * (-2.84817495755985104766e-02 + z * (-5.77027029648944159157e-03 + z * -2.37630166566501626084e-05)))
    let q = 1.0 + z * (3.97917223959155352819e-01 + z * (6.50222499887672944485e-02 + z * (5.08130628187576562776e-03 + z * (1.32494738004321644526e-04 + z * -3.96022827877536812320e-06))))
    return p / q

## erf(1 + s) - erx = P(s)/Q(s) on [0.84375, 1.25).
func erf_middle(s: f64) -> f64:
    let p = -2.36211856075265944077e-03 + s * (4.14856118683748331666e-01 + s * (-3.72207876035701323847e-01 + s * (3.18346619901161753674e-01 + s * (-1.10894694282396677476e-01 + s * (3.54783043256182359371e-02 + s * -2.16637559486879084300e-03)))))
    let q = 1.0 + s * (1.06420880400844228286e-01 + s * (5.40397917702171048937e-01 + s * (7.18286544141962662868e-02 + s * (1.26171219808761642112e-01 + s * (1.36370839120290507362e-02 + s * 1.19844998467991074170e-02)))))
    return p / q

## erfc(a) for 1.25 <= a < 28: exp(-a² - 0.5625 + R/S) / a. The square is split at a with
## its low 32 bits cleared, whose square is exact, so the exponent loses nothing.
func erfc_tail(a: f64) -> f64:
    let s = 1.0 / (a * a)
    var r: f64
    var q: f64
    if a < 2.857142857142857:
        r = -9.86494403484714822705e-03 + s * (-6.93858572707181764372e-01 + s * (-1.05586262253232909814e+01 + s * (-6.23753324503260060396e+01 + s * (-1.62396669462573470355e+02 + s * (-1.84605092906711035994e+02 + s * (-8.12874355063065934246e+01 + s * -9.81432934416914548592e+00))))))
        q = 1.0 + s * (1.96512716674392571292e+01 + s * (1.37657754143519042600e+02 + s * (4.34565877475229228821e+02 + s * (6.45387271733267880336e+02 + s * (4.29008140027567833386e+02 + s * (1.08635005541779435134e+02 + s * (6.57024977031928170135e+00 + s * -6.04244152148580987438e-02)))))))
    else:
        r = -9.86494292470009928597e-03 + s * (-7.99283237680523006574e-01 + s * (-1.77579549177547519889e+01 + s * (-1.60636384855821916062e+02 + s * (-6.37566443368389627722e+02 + s * (-1.02509513161107724954e+03 + s * -4.83519191608651397019e+02)))))
        q = 1.0 + s * (3.03380607434824582924e+01 + s * (3.25792512996573918826e+02 + s * (1.53672958608443695994e+03 + s * (3.19985821950859553908e+03 + s * (2.55305040643316442583e+03 + s * (4.74528541206955367215e+02 + s * -2.24409524465858183362e+01))))))
    let z = f64.bits(a.bits() & 0xffffffff00000000)
    return exp_value(-z * z - 0.5625) * exp_value((z - a) * (z + a) + r / q) / a

## The error function, (2/√π)∫₀ˣ e^(-t²) dt, as Python's `math.erf`: odd, from -1 to 1.
## Signed zero is preserved; infinities give ±1 and NaN gives NaN.
pub func erf(x: f64) -> f64:
    let a = abs(x)
    if not (a < 6.0):
        if is_nan(x):
            return x
        return copysign(1.0, x)
    if a < 0.84375:
        if a < 3.725290298461914e-09:
            # below 2^-28 the series is x + efx·x; scaling by 8 keeps subnormals exact
            return 0.125 * (8.0 * x + (8.0 * efx) * x)
        return x + x * erf_small(x)
    let magnitude = erx + erf_middle(a - 1.0) if a < 1.25 else 1.0 - erfc_tail(a)
    return copysign(magnitude, x)

## The complementary error function, `1 - erf(x)`, as Python's `math.erfc`: accurate where
## erf(x) is near 1 and the subtraction would lose every digit. It falls from 2 to 0 and
## underflows to zero above about 27.2; infinities give 0 and 2, NaN gives NaN.
pub func erfc(x: f64) -> f64:
    let a = abs(x)
    if a < 0.84375:
        if a < 1.3877787807814457e-17:
            return 1.0 - x
        let y = x * erf_small(x)
        if x < 0.25:
            return 1.0 - (x + y)
        return 0.5 - (y + (x - 0.5))
    if a < 1.25:
        let p = erf_middle(a - 1.0)
        return (1.0 - erx) - p if x > 0.0 else 1.0 + (erx + p)
    if a < 28.0:
        if x < -6.0:
            return 2.0
        let r = erfc_tail(a)
        return r if x > 0.0 else 2.0 - r
    if is_nan(x):
        return x
    return 0.0 if x > 0.0 else 2.0

## True for quiet and signaling NaNs, independent of sign and payload.
pub func is_nan(x: f64) -> bool:
    return (x.bits() & magnitude_mask) > exponent_mask

## True for zeros, subnormals and normal finite values. Classification inspects the
## representation and performs no floating-point arithmetic on a signaling NaN.
pub func is_finite(x: f64) -> bool:
    return (x.bits() & exponent_mask) != exponent_mask

## True only for positive or negative infinity.
pub func is_infinite(x: f64) -> bool:
    return (x.bits() & magnitude_mask) == exponent_mask

## Whether the sign bit is set, including negative zero and signed NaNs.
pub func signbit(x: f64) -> bool:
    return (x.bits() & sign_mask) != 0

## Clear the sign bit: negative zero becomes positive zero. NaN payload bits survive.
pub func abs(x: f64) -> f64:
    return c_fabs(x)

## The magnitude and payload of `magnitude` with the sign bit of `sign_source`.
pub func copysign(magnitude: f64, sign_source: f64) -> f64:
    return f64.bits((magnitude.bits() & magnitude_mask) | (sign_source.bits() & sign_mask))

## `-1.0` or `1.0` for nonzero numbers; zero and NaN are returned unchanged.
pub func sign(x: f64) -> f64:
    if is_nan(x):
        return x
    if x < 0.0:
        return -1.0
    if x > 0.0:
        return 1.0
    return x

## Minimum with NaN propagation (left NaN wins if both are NaNs). Negative zero
## wins over positive zero; a selected NaN retains its original bits.
pub func min(a: f64, b: f64) -> f64:
    if is_nan(a):
        return a
    if is_nan(b):
        return b
    if a == 0.0 and b == 0.0:
        return f64.bits(a.bits() | b.bits())
    return a if a < b else b

## Maximum with NaN propagation (left NaN wins if both are NaNs). Positive zero
## wins over negative zero; a selected NaN retains its original bits.
pub func max(a: f64, b: f64) -> f64:
    if is_nan(a):
        return a
    if is_nan(b):
        return b
    if a == 0.0 and b == 0.0:
        return f64.bits(a.bits() & b.bits())
    return a if a > b else b

## Restrict `x` to inclusive ordered bounds. Reversed or NaN bounds trap. An input
## NaN or an input equal to a bound is returned unchanged, including its zero sign.
pub func clamp(x: f64, low: f64, high: f64) -> f64:
    assert(low <= high)
    if is_nan(x):
        return x
    return low if x < low else (high if x > high else x)

## The integer functions. `//` and `%` truncate toward zero as C does (§7.2); these two
## floor, so `div_floor(-7, 2)` is `-4` and `mod_floor(-7, 2)` is `1`.
pub func div_floor(a: i64, b: i64) -> i64:
    let q = a // b
    if (a % b != 0) and ((a < 0) != (b < 0)):
        return q - 1
    return q

## The remainder of `a / b` with the divisor's sign (floored division).
pub func mod_floor(a: i64, b: i64) -> i64:
    if b == -1:
        return 0
    let r = a % b
    if r != 0 and ((r < 0) != (b < 0)):
        return r + b
    return r

## The absolute value of `a`; the minimum i64 wraps to itself.
pub func iabs(a: i64) -> i64:
    return 0 - a if a < 0 else a

## Absolute value, or none for the minimum i64 whose positive magnitude cannot fit.
pub func checked_iabs(a: i64) -> i64?:
    if a < 0:
        return 0 -? a
    return a

## Floor division, or none for a zero divisor or a quotient outside i64.
pub func checked_div_floor(a: i64, b: i64) -> i64?:
    if b == 0 or (a == -9223372036854775808 and b == -1):
        return none
    return div_floor(a, b)

## Remainder with the divisor's sign, or none for a zero divisor. The minimum i64
## modulo -1 is zero even though its quotient cannot be represented.
pub func checked_mod_floor(a: i64, b: i64) -> i64?:
    if b == 0:
        return none
    if b == -1:
        return 0
    return mod_floor(a, b)

## The smaller of `a` and `b`.
pub func imin(a: i64, b: i64) -> i64:
    return a if a < b else b

## The larger of `a` and `b`.
pub func imax(a: i64, b: i64) -> i64:
    return a if a > b else b

## Restrict `x` to inclusive ordered bounds. Reversed bounds trap.
pub func iclamp(x: i64, low: i64, high: i64) -> i64:
    assert(low <= high)
    return low if x < low else (high if x > high else x)