#! @file exact.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the operations of real numbers IEEE 754 defines to the bit: square #! roots, rounding to integers, absolute values, signs, fused multiplying and #! adding, and the least and greatest of two values. Each gives the one result #! the standard says, in the virtual machine, in an executable, and while #! compiling. #! #! An `f32` is worked in `f64` and rounded back, which gives its exact result #! too: a double holds more than twice a float's bits, so its square root #! rounds once, and a float's integer neighbours are floats. Only `fma` needs #! more, as musl's `fmaf` does. #! #! Where the processor has an instruction for one, as SSE4.1's `roundsd` and #! FMA3's `vfmadd231sd`, an executable works rounding and `fma` with it, of one #! number, as `lanes_apply` of one lane gives it, which gives the same bits, NaN #! included: the code here quiets a NaN it is given, as the instructions do. #! #! Rounding is ported from musl 1.2.5, which is Copyright © 2005-2020 Rich #! Felker, et al., under the MIT license. `fma_single` is from FreeBSD's #! s_fmaf.c, by way of musl, which says: #! #! Copyright (c) 2005-2011 David Schultz #! All rights reserved. #! #! Redistribution and use in source and binary forms, with or without #! modification, are permitted provided that the following conditions #! are met: #! 1. Redistributions of source code must retain the above copyright #! notice, this list of conditions and the following disclaimer. #! 2. Redistributions in binary form must reproduce the above copyright #! notice, this list of conditions and the following disclaimer in the #! documentation and/or other materials provided with the distribution. #! #! THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND #! ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #! ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE #! FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL #! DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS #! OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) #! HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT #! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY #! OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF #! SUCH DAMAGE. import core::intrinsics; module std::math; #! The square root of a real, correctly rounded. #! @tparam T The type of real. #! @param x The real. #! @returns Its square root: `-0` for `-0`, infinity for infinity, and NaN for #! what is below zero or NaN. pub def sqrt(x: T): T where T: real { return square_root(x as f64) as T; } #! The greatest integer not above a real. #! @tparam T The type of real. #! @param x The real. #! @returns The integer, as a real: `-0` stays `-0`, and infinities and NaN #! are themselves. pub def floor(x: T): T where T: real { return lane_alone::(x, x, x) if lanes_have::(); return floor_double(x as f64) as T; } #! The least integer not below a real. #! @tparam T The type of real. #! @param x The real. #! @returns The integer, as a real: what is above -1 and below 0 gives `-0`. pub def ceil(x: T): T where T: real { return lane_alone::(x, x, x) if lanes_have::(); return ceil_double(x as f64) as T; } #! A real's integer part, toward zero. #! @tparam T The type of real. #! @param x The real. #! @returns The integer, as a real, of the real's sign. pub def trunc(x: T): T where T: real { return lane_alone::(x, x, x) if lanes_have::(); return trunc_double(x as f64) as T; } #! The integer nearest a real, halves away from zero, so 2.5 gives 3 and -2.5 #! gives -3. #! @tparam T The type of real. #! @param x The real. #! @returns The integer, as a real, of the real's sign. pub def round(x: T): T where T: real { if lanes_have::() { # What truncating leaves is exact, so a half or more rounds away. val whole := lane_alone::(x, x, x); val part := (x - whole) as f64; return whole + copysign(1 as T, x) if part >= 0.5 || part <= -0.5; return whole; } return round_double(x as f64) as T; } #! The integer nearest a real, halves to the even one, so 2.5 gives 2 and 3.5 #! gives 4, as IEEE 754 rounds by default. #! @tparam T The type of real. #! @param x The real. #! @returns The integer, as a real, of the real's sign. pub def round_even(x: T): T where T: real { return lane_alone::(x, x, x) if lanes_have::(); return round_even_double(x as f64) as T; } #! A value's distance from zero, of a type that negates and is ordered: a #! number, or a `duration`. A real's sign bit is cleared, so `-0` gives `0`, and #! NaN a NaN. The most negative integer of a type has no positive, and gives #! itself. #! @tparam T The type. #! @param x The value. #! @returns Its absolute value. pub def abs(x: T): T where T: negatable, ordered { if const T is real { if const size_of::() == 4 { return real_of_bits(bits_of(x as f32) & 0x7FFFFFFF) as T; } return real_of_bits(bits_of(x as f64) & 0x7FFFFFFFFFFFFFFF) as T; } return x < -x ? -x : x; } #! A real with the magnitude of one and the sign of another, NaN included. #! @tparam T The type of real. #! @param x The real giving the magnitude. #! @param sign The real giving the sign. #! @returns The real. pub def copysign(x: T, sign: T): T where T: real { if const size_of::() == 4 { return real_of_bits((bits_of(x as f32) & 0x7FFFFFFF) | (bits_of(sign as f32) & 0x80000000)) as T; } return real_of_bits((bits_of(x as f64) & 0x7FFFFFFFFFFFFFFF) | (bits_of(sign as f64) & 0x8000000000000000)) as T; } #! `x * y + z`, rounded once rather than after the multiply too. Where the #! processor has FMA3, its instruction works it, which rounds once too, so it #! gives the same bits, and the same NaN: a factor's, `x`'s before `y`'s, and #! otherwise `z`'s, even where the product is NaN, as `∞ * 0` is. #! @tparam T The type of real. #! @param x The first factor. #! @param y The second factor. #! @param z What the product is added to. #! @returns The sum, correctly rounded. pub def fma(x: T, y: T, z: T): T where T: real { return lane_alone::(x, y, z) if lanes_have::(); if const size_of::() == 4 { return fma_single(x as f32, y as f32, z as f32) as T; } return fma_double(x as f64, y as f64, z as f64) as T; } # The operation `OP` of one real, as `lanes_apply` of one lane works it with the # instruction of one number, where `lanes_have` says the processor has it: of # `a`, or of all three for `fma`. def lane_alone(a: T, b: T, c: T): T where T: real { var made: T = 0; lanes_apply::((&mut made) as *mut u8, (&a) as *u8, (&b) as *u8, (&c) as *u8); return made; } #! The lesser of two values. Of reals, this is IEEE 754's `minimum`: NaN where #! either is NaN, and `-0` below `0`. Of others, `a` where they are equal. #! @tparam T The type. #! @param a One value. #! @param b The other. #! @returns The lesser. pub def min(a: T, b: T): T where T: ordered { if const T is real { return a + b if a != a || b != b; if a == b { return sign_bit(a) ? a : b; } } return b < a ? b : a; } #! The greater of two values. Of reals, this is IEEE 754's `maximum`: NaN where #! either is NaN, and `0` above `-0`. Of others, `a` where they are equal. #! @tparam T The type. #! @param a One value. #! @param b The other. #! @returns The greater. pub def max(a: T, b: T): T where T: ordered { if const T is real { return a + b if a != a || b != b; if a == b { return sign_bit(a) ? b : a; } } return a < b ? b : a; } #! A value held between two others, as `max(low, min(x, high))`: `low` where it #! is below, `high` where it is above, and itself between. Of reals, NaN gives #! NaN. Where `low` is above `high`, it gives `low`. #! @tparam T The type. #! @param x The value. #! @param low The least it may be. #! @param high The greatest it may be. #! @returns The value held. pub def clamp(x: T, low: T, high: T): T where T: ordered { return max(low, min(x, high)); } # Doubles. # 2^52, past which every double is an integer, and which adding and taking away # rounds a smaller one to an integer. const to_integer: f64 = 4503599627370496.0; def floor_double(x: f64): f64 { return x + x if x != x; val bits := bits_of(x); val e := (bits >> 52) & 0x7FF; return x if e >= 0x3FF + 52 || x == 0; # y is the integer nearest x, less x. val y := (bits >> 63) != 0 ? x - to_integer + to_integer - x : x + to_integer - to_integer - x; if e <= 0x3FF - 1 { return (bits >> 63) != 0 ? -1.0 : 0.0; } return x + y - 1.0 if y > 0; return x + y; } def ceil_double(x: f64): f64 { return x + x if x != x; val bits := bits_of(x); val e := (bits >> 52) & 0x7FF; return x if e >= 0x3FF + 52 || x == 0; val y := (bits >> 63) != 0 ? x - to_integer + to_integer - x : x + to_integer - to_integer - x; if e <= 0x3FF - 1 { return (bits >> 63) != 0 ? -0.0 : 1.0; } return x + y + 1.0 if y < 0; return x + y; } def trunc_double(x: f64): f64 { return x + x if x != x; val bits := bits_of(x); var e := (((bits >> 52) & 0x7FF) as i64) - 0x3FF + 12; return x if e >= 52 + 12; if e < 12 { e = 1; } val m := 0xFFFFFFFFFFFFFFFFu >> (e as u64); return x if (bits & m) == 0; return real_of_bits(bits & ~m); } def round_double(x: f64): f64 { return x + x if x != x; val bits := bits_of(x); val e := (bits >> 52) & 0x7FF; return x if e >= 0x3FF + 52; val negative := (bits >> 63) != 0; val a := negative ? -x : x; if e < 0x3FF - 1 { return 0.0 * x; } var y := a + to_integer - to_integer - a; if y > 0.5 { y = y + a - 1.0; } else if y <= -0.5 { y = y + a + 1.0; } else { y = y + a; } return negative ? -y : y; } def round_even_double(x: f64): f64 { return x + x if x != x; val bits := bits_of(x); val e := (bits >> 52) & 0x7FF; return x if e >= 0x3FF + 52; val negative := (bits >> 63) != 0; val y := negative ? x - to_integer + to_integer : x + to_integer - to_integer; if y == 0 { return negative ? -0.0 : 0.0; } return y; } # x times 2^n, rounded once: musl's `scalbn`. def scalbn(x: f64, power: i32): f64 { var n := power; var y := x; if n > 1023 { y *= 8.98846567431158e307; n -= 1023; if n > 1023 { y *= 8.98846567431158e307; n -= 1023; if n > 1023 { n = 1023; } } } else if n < -1022 { # The last n is below -53, so a subnormal result rounds once. y *= 2.2250738585072014e-308 * 9007199254740992.0; n += 1022 - 53; if n < -1022 { y *= 2.2250738585072014e-308 * 9007199254740992.0; n += 1022 - 53; if n < -1022 { n = -1022; } } } return y * real_of_bits(((0x3FF + n) as u64) << 52); } # Fused multiplying and adding, of doubles, from musl's fma.c: the product is # held exactly in 128 bits, the sum is formed in them, and the result is rounded # once converting to a double. # A double as its significand, shifted so its top 10 bits and its last are 0, # its exponent, and its sign. struct fma_part { var m: u64; var e: i32; var sign: i32; } # Exponents from this one up are of zero, infinity, or NaN. const zero_inf_nan: i32 = 0x7FF - 0x3FF - 52 - 1; def fma_normalize(x: f64): fma_part { var ix := bits_of(x); var e := (ix >> 52) as i32; val sign := e & 0x800; e &= 0x7FF; if e == 0 { ix = bits_of(x * 9223372036854775808.0); e = ((ix >> 52) & 0x7FF) as i32; e = e != 0 ? e - 63 : 0x800; } ix &= (1u << 52) - 1; ix |= 1u << 52; ix <<= 1; e -= 0x3FF + 52 + 1; return fma_part { m = ix, e = e, sign = sign }; } # 1 where a word is not zero, as C's `!!`. def any_of(word: u64): u64 { return word != 0 ? 1 : 0; } def fma_double(x: f64, y: f64, z: f64): f64 { # A NaN added to factors that aren't is what it gives, quieted, as FMA3 does, # though their product is NaN. return z + z if z != z && x == x && y == y; val nx := fma_normalize(x); val ny := fma_normalize(y); val nz := fma_normalize(z); return x * y + z if nx.e >= zero_inf_nan || ny.e >= zero_inf_nan; if nz.e >= zero_inf_nan { return x * y + z if nz.e > zero_inf_nan; return z; } # r = x * y, of 128 bits. val xlo := nx.m & 0xFFFFFFFF; val xhi := nx.m >> 32; val ylo := ny.m & 0xFFFFFFFF; val yhi := ny.m >> 32; val t1 := xlo * ylo; val t2 := xlo * yhi + xhi * ylo; val t3 := xhi * yhi; var rlo := t1 + (t2 << 32); var rhi := t3 + (t2 >> 32) + (t1 > rlo ? 1u : 0u); # The exponents aligned: z shifted left by kz and r right by kr, where kz + kr # is d, and e is then e + kr. var zlo: u64 = 0; var zhi: u64 = 0; var e := nx.e + ny.e; var d := nz.e - e; if d > 0 { if d < 64 { zlo = nz.m << (d as u64); zhi = nz.m >> ((64 - d) as u64); } else { zlo = 0; zhi = nz.m; e = nz.e - 64; d -= 64; if d == 0 { } else if d < 64 { rlo = (rhi << ((64 - d) as u64)) | (rlo >> (d as u64)) | any_of(rlo << ((64 - d) as u64)); rhi = rhi >> (d as u64); } else { rlo = 1; rhi = 0; } } } else { zhi = 0; d = -d; if d == 0 { zlo = nz.m; } else if d < 64 { zlo = (nz.m >> (d as u64)) | any_of(nz.m << ((64 - d) as u64)); } else { zlo = 1; } } # The sum. var sign := nx.sign ^ ny.sign; val same_sign := (sign ^ nz.sign) == 0; var nonzero := true; if same_sign { rlo += zlo; rhi += zhi + (rlo < zlo ? 1u : 0u); } else { val t := rlo; rlo -= zlo; rhi = rhi - zhi - (t < rlo ? 1u : 0u); if (rhi >> 63) != 0 { rlo = 0 - rlo; rhi = (0 - rhi) - any_of(rlo); sign = sign != 0 ? 0 : 1; } nonzero = rhi != 0; } # rhi is the top 63 bits of the result, its last bit sticky. if nonzero { e += 64; d = (leading_zeros(rhi) as i32) - 1; rhi = (rhi << (d as u64)) | (rlo >> ((64 - d) as u64)) | any_of(rlo << (d as u64)); } else if rlo != 0 { d = (leading_zeros(rlo) as i32) - 1; if d < 0 { rhi = (rlo >> 1) | (rlo & 1); } else { rhi = rlo << (d as u64); } } else { # An exact zero, of the sign the operations give it. return x * y + z; } e -= d; # The double, from |r| in [2^62, 2^63]. var i := rhi as i64; if sign != 0 { i = -i; } var r := i as f64; if e < -1022 - 62 { # Subnormal before rounding. if e == -1022 - 63 { var c: f64 = 9223372036854775808.0; if sign != 0 { c = -c; } if r == c { # The least normal value, after rounding. return sign != 0 ? -2.2250738585072014e-308 : 2.2250738585072014e-308; } # A bit is lost scaling, so another top bit is added to round once, at # converting, where it is inexact. if (rhi << 53) != 0 { i = ((rhi >> 1) | (rhi & 1) | (1u << 62)) as i64; if sign != 0 { i = -i; } r = i as f64; r = 2.0 * r - c; } } else { # Rounded once, scaling. i = (((rhi >> 10) | any_of(rhi << 54)) << 10) as i64; if sign != 0 { i = -i; } r = i as f64; } } return scalbn(r, e); } # Fused multiplying and adding, of floats, from FreeBSD's s_fmaf.c: the product # is exact in a double, and so is the sum but where it rounds to a halfway point # between two floats, which the error then moves off. def fma_single(x: f32, y: f32, z: f32): f32 { return z + z if z != z && x == x && y == y; val xy := (x as f64) * (y as f64); val wide := z as f64; val result := xy + wide; var bits := bits_of(result); val e := (bits >> 52) & 0x7FF; if (bits & 0x1FFFFFFF) != 0x10000000 || e == 0x7FF || (result - xy == wide && result - wide == xy) { return result as f32; } val negative := (bits >> 63) != 0; val error := negative == (wide > xy) ? xy - result + wide : wide - result + xy; if negative == (error < 0) { bits++; } else { bits--; } return real_of_bits(bits) as f32; }