plum

#treesitter#compiler#wasm

git clone https://git.pyrossh.dev/plum

A statically typed, imperative programming language inspired by rust, python


268fe32 — Peter John 2026-11-10T11:34:45+05:30
std math: fdlibm sin, cos and tan with Cody-Waite and Payne-Hanek reduction
benchmarks/math_bits/check.plum CHANGED
@@ -1,10 +1,9 @@
1
1
  # Bit-identity check for std math's unrolled series and bit-based range reduction: runs the
2
2
  # loop versions std had before (kept here only, as `old*`) and std's current ones over the
3
3
  # same deterministic inputs and counts results whose 64 bits differ (NaN payloads and the
4
- # sign of zero included). The edge fix made since (`sin` keeps a zero's sign) is copied into
4
+ # sign of zero included). `sin`, `cos`, `tan` and `atan` are no longer compared: they are now
5
- # the old version too, so only the unrolling is compared. `atan` is no longer compared: it is
6
- # now fdlibm's (under 1 ulp; the old series was up to 165 ulp off) and was checked against
5
+ # fdlibm's (under 1 ulp; the old series were up to 10^22 and 165 ulp off) and were checked
7
- # mpmath instead. `logb` now reads the exponent from the bits; it is checked against an
6
+ # against mpmath instead. `logb` now reads the exponent from the bits; it is checked against an
8
7
  # exact halve-or-double reference instead (the old `floor(ln(|x|) * Log2E)` was wrong for
9
8
  # about 40% of the floats just below a power of two).
10
9
  #
@@ -90,35 +89,6 @@ fun oldLnSeries(t2: Float, term: Float, sum: Float, n: Int) -> Float =
90
89
  else
91
90
  sum
92
91
 
93
- fun oldReduceToPi(x: Float) -> Float =
94
- k := {x / Float.Tau + {if x >= 0.0f then 0.5f else -0.5f}}.trunc()
95
- x - k * Float.Tau
96
-
97
- fun oldSin(x: Float) -> Float =
98
- if x != x || x > Float.Max || x < -Float.Max
99
- 0.0f / 0.0f
100
- else if x == 0.0f
101
- x
102
- else
103
- r := oldReduceToPi(x)
104
- oldSinSeries(r * r, r, r, 1)
105
-
106
- fun oldSinSeries(r2: Float, term: Float, sum: Float, n: Int) -> Float =
107
- if n < 10
108
- t := term * {-r2} / Float({2 * n} * {2 * n + 1})
109
- oldSinSeries(r2, t, sum + t, n + 1)
110
- else
111
- sum
112
-
113
- fun oldCos(x: Float) -> Float =
114
- if x != x || x > Float.Max || x < -Float.Max
115
- 0.0f / 0.0f
116
- else
117
- oldSin(x + Float.HalfPi)
118
-
119
- fun oldTan(x: Float) -> Float =
120
- oldSin(x) / oldCos(x)
121
-
122
92
  fun oldPow(base: Float, y: Float) -> Float =
123
93
  if y == 0.0f
124
94
  1.0f
@@ -295,15 +265,12 @@ fun main(io: Io) =
295
265
  io.printLn("inputs: {kinds(0, n, 0, 0, 0, 0, 0)}")
296
266
  # the check finds a difference when there is one
297
267
  # (counting from 3: no mismatch lines)
298
- sanity := sweep1(io, |x| oldSin(x), |x| math.cos(x), 0, 1000, 3) - 3
268
+ sanity := sweep1(io, |x| oldExp(x), |x| math.ln(x), 0, 1000, 3) - 3
299
- io.printLn("sanity (old sin against cos): {sanity} of 1000 differ")
269
+ io.printLn("sanity (old exp against ln): {sanity} of 1000 differ")
300
- b1 := report(io, "sin", n, sweep1(io, |x| oldSin(x), |x| math.sin(x), 0, n, 0))
301
- b2 := report(io, "cos", n, sweep1(io, |x| oldCos(x), |x| math.cos(x), 0, n, 0))
302
- b3 := report(io, "tan", n, sweep1(io, |x| oldTan(x), |x| math.tan(x), 0, n, 0))
303
270
  b4 := report(io, "exp", n, sweep1(io, |x| oldExp(x), |x| math.exp(x), 0, n, 0))
304
271
  b5 := report(io, "exp near +-2^-2..2^10", 4001 * 26, sweepGen(io, |i| expEdge(i), |x| oldExp(x), |x| math.exp(x), 0, 4001 * 26, 0))
305
272
  b6 := report(io, "ln", n, sweep1(io, |x| oldLn(x), |x| math.ln(x), 0, n, 0))
306
273
  b7 := report(io, "ln near every 2^e", 101 * 2047, sweepGen(io, |i| lnEdge(i), |x| oldLn(x), |x| math.ln(x), 0, 101 * 2047, 0))
307
274
  b9 := report(io, "logb (against an exact reference)", n, sweep1(io, |x| refLogb(x), |x| x.logb(), 0, n, 0))
308
275
  b10 := report(io, "pow", n, sweep2(io, |x, y| oldPow(x, y), |x, y| x.pow(y), 0, n, 0))
309
- io.printLn("mismatches {b1 + b2 + b3 + b4 + b5 + b6 + b7 + b9 + b10}")
276
+ io.printLn("mismatches {b4 + b5 + b6 + b7 + b9 + b10}")
compiler/wasm-codegen/tests/wasm_codegen/native_test.rs CHANGED
@@ -153,7 +153,7 @@ fn float_bits_compile_to_reinterprets_and_series_have_no_loop() {
153
153
  assert_eq!(count(f("ln"), "I64ReinterpretF64"), 2, "{:?}", f("ln"));
154
154
  assert_eq!(count(f("ln"), "Loop"), 0, "{:?}", f("ln"));
155
155
  assert_eq!(count(f("lnBits"), "F64ReinterpretI64"), 1, "{:?}", f("lnBits"));
156
- for s in ["sinSeries", "expSeries", "lnSeries", "atanPoly"] {
156
+ for s in ["sinKernel0", "sinKernel", "cosKernel", "tanPoly", "expSeries", "lnSeries", "atanPoly"] {
157
157
  let ops = f(s);
158
158
  assert_eq!(count(ops, "Call") + count(ops, "ReturnCall") + count(ops, "Loop") + count(ops, "F64ConvertI64S"), 0, "{s}: {ops:?}");
159
159
  }
docs/std.md CHANGED
@@ -38,9 +38,9 @@ fun main() =
38
38
  - `Float`: `abs`, `sqrt`, `pow`, `floor`, `ceil`, `round`, `trunc`, `isNaN`, `toStr`, `Float.parse`, `Float.Pi`, `Float.Tau`, `Float.E`, and `toBits` / `Float.fromBits` between a Float and its 64 IEEE 754 bits as an Int
39
39
  - `math`: `math.sqrt`, `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`, `exp`, `ln`, `hypot`, `cbrt`
40
40
 
41
- Where wasm has the operation, std uses its instruction, compiled in line at each call: `math.sqrt` and `Float.sqrt` are `f64.sqrt`, correctly rounded; `abs`, `floor`, `ceil` and `trunc` are `f64.abs`, `f64.floor`, `f64.ceil` and `f64.trunc`; `leadingZeros`, `trailingZeros` and `popCount` are `i64.clz`, `i64.ctz` and `i64.popcnt`; `x.toBits()` and `Float.fromBits(b)` are `i64.reinterpret_f64` and `f64.reinterpret_i64`, so a NaN keeps its payload and `{-0.0}.toBits()` is `Int.Min`. These are exact for every Float: NaN and the infinities pass through, a value past `Int`'s range comes back whole as it was, and a zero keeps its sign (`{-0.5}.floor()` is `-1.0`, `{-0.5}.ceil()` is `-0.0`, `{-0.0}.abs()` is `0.0`). `round` is half away from zero and exact too (`0.49999999999999994.round()` is `0.0`). `math.hypot(a, b)` is `sqrt(a * a + b * b)` unless that sum overflows or underflows, then it scales: `hypot(3e200, 4e200)` is about `5e200`, and an infinite side gives Infinity even next to a NaN. `min` and `max` stay comparisons: `x.min(y)` is `if x < y then x else y`, so with a NaN it returns `y`. `sin`, `cos`, `exp`, `ln` and the rest have no wasm instruction and are Plum code made of exact IEEE operations, so they give the same bits on every host. Their series are written out term by term (no loop), and `ln` reads the power of two of its argument from the exponent bits instead of halving or doubling it, as `exp` does for the scaling into [-0.5, 0.5]; `benchmarks/math_bits/check.plum` checks that these give the same bits as the loop versions did.
41
+ Where wasm has the operation, std uses its instruction, compiled in line at each call: `math.sqrt` and `Float.sqrt` are `f64.sqrt`, correctly rounded; `abs`, `floor`, `ceil` and `trunc` are `f64.abs`, `f64.floor`, `f64.ceil` and `f64.trunc`; `leadingZeros`, `trailingZeros` and `popCount` are `i64.clz`, `i64.ctz` and `i64.popcnt`; `x.toBits()` and `Float.fromBits(b)` are `i64.reinterpret_f64` and `f64.reinterpret_i64`, so a NaN keeps its payload and `{-0.0}.toBits()` is `Int.Min`. These are exact for every Float: NaN and the infinities pass through, a value past `Int`'s range comes back whole as it was, and a zero keeps its sign (`{-0.5}.floor()` is `-1.0`, `{-0.5}.ceil()` is `-0.0`, `{-0.0}.abs()` is `0.0`). `round` is half away from zero and exact too (`0.49999999999999994.round()` is `0.0`). `math.hypot(a, b)` is `sqrt(a * a + b * b)` unless that sum overflows or underflows, then it scales: `hypot(3e200, 4e200)` is about `5e200`, and an infinite side gives Infinity even next to a NaN. `min` and `max` stay comparisons: `x.min(y)` is `if x < y then x else y`, so with a NaN it returns `y`. `sin`, `cos`, `exp`, `ln` and the rest have no wasm instruction and are Plum code made of exact IEEE operations, so they give the same bits on every host. Their series and polynomials are written out term by term (no loop), and `ln` reads the power of two of its argument from the exponent bits instead of halving or doubling it, as `exp` does for the scaling into [-0.5, 0.5]; `benchmarks/math_bits/check.plum` checks that these give the same bits as the loop versions did.
42
42
 
43
- At the edges they follow IEEE 754. `x.logb()` is the exponent of `|x|`, floor(log2(|x|)) exactly, read from the bits (a subnormal is scaled by 2^54 first): `7.999999999999999.logb()` is `2.0`, `Float.Min.logb()` is `-1074.0`, `logb` of a zero is -Infinity, of either infinity Infinity, of NaN NaN, and the sign is ignored (`Int.logb` agrees: `Int.Min.logb()` is `63.0`). `math.cbrt` is correctly rounded (no miss in a million sampled inputs over every exponent) for every Float, subnormals and `1e300` included (`cbrt(1e300)` is `1e100`): `|x|` is split into `m * 2^(3k)` from the bits, FreeBSD's `s_cbrt.c` guess gives a 23-bit root `t` of `m`, and `t * (1 + u)^(1/3)` with `u = (m - t^3) / t^3` (the residual exact but for one rounding, by Dekker's product; the binomial series to u^4) rounds to the nearest float unless the root is within about 2^-22 ulp of halfway. It keeps the sign (`cbrt(-0.0)` is `-0.0`), and NaN and the infinities pass through. `math.atan` is fdlibm's `s_atan.c` bit for bit, under 1 ulp (0.70 at worst over 40k sampled inputs against mpmath): breakpoints at 7/16, 11/16, 19/16 and 39/16, then a degree-22 odd polynomial; from 2^66 up, and at the infinities, it is `±Pi/2`. `math.atan2` is fdlibm's `e_atan2.c` (1.36 ulp at worst) with C99's special cases: `atan2(±0, x)` is `±0` for `x` above zero or `+0` and `±Pi` for `x` below zero or `-0`, `atan2(y, ±0)` for a nonzero `y` is `±Pi/2`, an infinite `x` gives `±0` or `±Pi` for a finite `y` and `±Pi/4` or `±3*Pi/4` for an infinite one, an infinite `y` gives `±Pi/2`, and a NaN on either side gives NaN. `math.asin` is `atan(x / sqrt(1 - x*x))` with `(1 - x) * (1 + x)` from `|x| = 0.5` up, and `math.acos` is `2 * atan(sqrt((1 - x) / (1 + x)))`, both within 1.8 ulp (`acos` was `Pi/2 - asin(x)`, 231 ulp off near 1). `sin(-0.0)`, `tan(-0.0)`, `asin(-0.0)` and `atan(-0.0)` are `-0.0`.
43
+ At the edges they follow IEEE 754. `x.logb()` is the exponent of `|x|`, floor(log2(|x|)) exactly, read from the bits (a subnormal is scaled by 2^54 first): `7.999999999999999.logb()` is `2.0`, `Float.Min.logb()` is `-1074.0`, `logb` of a zero is -Infinity, of either infinity Infinity, of NaN NaN, and the sign is ignored (`Int.logb` agrees: `Int.Min.logb()` is `63.0`). `math.cbrt` is correctly rounded (no miss in a million sampled inputs over every exponent) for every Float, subnormals and `1e300` included (`cbrt(1e300)` is `1e100`): `|x|` is split into `m * 2^(3k)` from the bits, FreeBSD's `s_cbrt.c` guess gives a 23-bit root `t` of `m`, and `t * (1 + u)^(1/3)` with `u = (m - t^3) / t^3` (the residual exact but for one rounding, by Dekker's product; the binomial series to u^4) rounds to the nearest float unless the root is within about 2^-22 ulp of halfway. It keeps the sign (`cbrt(-0.0)` is `-0.0`), and NaN and the infinities pass through. `math.sin`, `math.cos` and `math.tan` are fdlibm's (FreeBSD's `s_sin.c`, `s_cos.c`, `s_tan.c`), under 1 ulp for every finite Float: against mpmath over 89k sampled inputs (every exponent, multiples of Pi/2 and the floats next to them, subnormals) at worst 0.72, 0.74 and 0.81 ulp, with 1.4%, 1.5% and 1.7% not the nearest float (the old Taylor series after a plain subtraction of multiples of 2*Pi was up to 10^22 ulp off next to the zeros, and for |x| <= 4 36%, 68% and 68% not the nearest). `x` is reduced to `n * Pi/2 + r` with `|r| <= Pi/4`: below 2^20 * Pi/2 (about 1.6e6) by Cody and Waite's subtraction with Pi/2 in three 33-bit parts, above it by multiplying the 53-bit significand by 240 bits of 2/Pi in integers (Payne and Hanek), so `sin(1e22)` is `-0.8522008497671888` and `sin(Float.Max)` is right too; then fdlibm's kernel polynomials for sin, cos and tan on `r`. A tiny `x` (below 2^-26 for `sin`, 2^-27 for `tan`) is its own `sin` and `tan`, a subnormal included, and its `cos` is `1.0`; the infinities and NaN give NaN. `math.atan` is fdlibm's `s_atan.c` bit for bit, under 1 ulp (0.70 at worst over 40k sampled inputs against mpmath): breakpoints at 7/16, 11/16, 19/16 and 39/16, then a degree-22 odd polynomial; from 2^66 up, and at the infinities, it is `±Pi/2`. `math.atan2` is fdlibm's `e_atan2.c` (1.36 ulp at worst) with C99's special cases: `atan2(±0, x)` is `±0` for `x` above zero or `+0` and `±Pi` for `x` below zero or `-0`, `atan2(y, ±0)` for a nonzero `y` is `±Pi/2`, an infinite `x` gives `±0` or `±Pi` for a finite `y` and `±Pi/4` or `±3*Pi/4` for an infinite one, an infinite `y` gives `±Pi/2`, and a NaN on either side gives NaN. `math.asin` is `atan(x / sqrt(1 - x*x))` with `(1 - x) * (1 + x)` from `|x| = 0.5` up, and `math.acos` is `2 * atan(sqrt((1 - x) / (1 + x)))`, both within 1.8 ulp (`acos` was `Pi/2 - asin(x)`, 231 ulp off near 1). `sin(-0.0)`, `tan(-0.0)`, `asin(-0.0)` and `atan(-0.0)` are `-0.0`.
44
44
 
45
45
  `Int.toStr` prints every Int, `Int.Min` as `-9223372036854775808`. `Float.toStr` rounds to 6 fractional digits below 2^63; from 2^63 up (past Int's range, where every Float is whole) it prints the float's exact decimal value, so `1.0e20.toStr()` is `100000000000000000000.0` and `Float.Max` prints all 309 digits. `Float.hash` is the bits (`toBits`), so values in (-1, 1) no longer collide in a `Map`; `0.0` and `-0.0`, which are `==`, both hash to 0, and every NaN hashes the same.
46
46
  - `Bool`: `toStr`, `Bool.parse`
std/math.plum CHANGED
@@ -153,48 +153,281 @@ fun lnSeries(t2: Float, t: Float) -> Float =
153
153
  fun sqrt(x: Float) -> Float =
154
154
  todo
155
155
 
156
+ # Sine, fdlibm's `s_sin.c` (FreeBSD's, under 1 ulp): `|x| <= Pi/4` goes straight to the
156
- # Reduces `x` into roughly `[-Float.Pi, Float.Pi]` by subtracting the nearest multiple of
157
+ # kernel, anything bigger is first reduced to `x - n * Pi/2` (see `trigReduce`) and the kernel
157
- # `Float.Tau` — the range `sin`/`cos`'s Taylor series below actually converge
158
+ # for `n mod 4` taken. Below 2^-26 `sin(x)` is `x`, so `sin(-0.0)` is `-0.0`; the infinities
158
- # quickly over. For very large `|x|` (many multiples of `Float.Tau`), floating-point
159
- # cancellation in `x - k*Float.Tau` loses precision the same way any naive
160
- # range-reduction by subtraction does; a real libm uses extended-precision
161
- # constants to avoid this, which isn't attempted here.
162
- fun reduceToPi(x: Float) -> Float =
163
- k := {x / Float.Tau + {if x >= 0.0f then 0.5f else -0.5f}}.trunc()
164
- x - k * Float.Tau
159
+ # and NaN give NaN.
165
-
166
- # `sin(-0.0)` is `-0.0`, as IEEE 754 has it.
167
160
  fun sin(x: Float) -> Float =
161
+ h := {x.toBits() & 0x7FFF_FFFF_FFFF_FFFF} >> 32
162
+ if h <= 0x3FE9_21FB
168
- if x != x || x > Float.Max || x < -Float.Max
163
+ if h < 0x3E50_0000 then x else sinKernel0(x)
169
- 0.0f / 0.0f
170
- else if x == 0.0f
164
+ else if h >= 0x7FF0_0000
171
- x
165
+ x - x
172
166
  else
173
- r := reduceToPi(x)
167
+ trigReduce(0, x, h)
174
- sinSeries(r, -{r * r})
175
-
176
- # The Taylor series of sin(r) to the r^19 term, in order: term n is term n-1 times -r^2 over
177
- # 2n(2n+1).
178
- fun sinSeries(r: Float, m: Float) -> Float =
179
- t1 := r * m / 6.0f
180
- t2 := t1 * m / 20.0f
181
- t3 := t2 * m / 42.0f
182
- t4 := t3 * m / 72.0f
183
- t5 := t4 * m / 110.0f
184
- t6 := t5 * m / 156.0f
185
- t7 := t6 * m / 210.0f
186
- t8 := t7 * m / 272.0f
187
- t9 := t8 * m / 342.0f
188
- r + t1 + t2 + t3 + t4 + t5 + t6 + t7 + t8 + t9
189
168
 
169
+ # Cosine, fdlibm's `s_cos.c`: as `sin`, with the quadrant one further on. Below 2^-27 * sqrt(2)
170
+ # `cos(x)` is `1.0`.
190
171
  fun cos(x: Float) -> Float =
172
+ h := {x.toBits() & 0x7FFF_FFFF_FFFF_FFFF} >> 32
173
+ if h <= 0x3FE9_21FB
191
- if x != x || x > Float.Max || x < -Float.Max
174
+ if h < 0x3E46_A09E then 1.0f else cosKernel(x, 0.0f)
192
- 0.0f / 0.0f
175
+ else if h >= 0x7FF0_0000
176
+ x - x
193
177
  else
194
- sin(x + Float.HalfPi)
178
+ trigReduce(1, x, h)
195
179
 
180
+ # Tangent, fdlibm's `s_tan.c`: the reduction of `sin`, then fdlibm's `__kernel_tan`, which
181
+ # gives `tan` or `-1/tan` by the parity of `n`. Below 2^-27 `tan(x)` is `x`, so `tan(-0.0)` is
182
+ # `-0.0`.
196
183
  fun tan(x: Float) -> Float =
197
- sin(x) / cos(x)
184
+ h := {x.toBits() & 0x7FFF_FFFF_FFFF_FFFF} >> 32
185
+ if h <= 0x3FE9_21FB
186
+ if h < 0x3E40_0000 then x else tanKernel(x, 0.0f, 1)
187
+ else if h >= 0x7FF0_0000
188
+ x - x
189
+ else
190
+ trigReduce(2, x, h)
191
+
192
+ # fdlibm's `e_rem_pio2.c`: `x = n * Pi/2 + (y0 + y1)` with `|y0 + y1| <= Pi/4` (about), then
193
+ # `trigAt` for `op` (0 sin, 1 cos, 2 tan). `h` is the high word of `|x|`. Below 2^20 * Pi/2,
194
+ # `n` is `x * 2/Pi` rounded and Pi/2 is taken off in three 33-bit parts (Cody and Waite),
195
+ # each product with `n` exact: the second part only when the first result's exponent is more
196
+ # than 16 below `x`'s, the third when more than 49 (a cancellation near a multiple of Pi/2).
197
+ # Above that,
198
+ # `trigHuge` multiplies by 2/Pi's bits in integers (Payne and Hanek).
199
+ fun trigReduce(op: Int, x: Float, h: Int) -> Float =
200
+ if h < 0x4139_21FB
201
+ # the nearest integer: 1.5 * 2^52 makes the sum round at the units
202
+ fn := {x * 6.36619772367581382433e-01 + 6755399441055744.0f} - 6755399441055744.0f
203
+ r := x - fn * 1.57079632673412561417e+00
204
+ w := fn * 6.07710050650619224932e-11
205
+ y := r - w
206
+ if {h >> 20} - {{y.toBits() >> 52} & 0x7FF} > 16
207
+ trigReduce2(op, Int(fn), fn, h >> 20, r)
208
+ else
209
+ trigAt(op, Int(fn), y, {r - y} - w)
210
+ else
211
+ trigHuge(op, x)
212
+
213
+ # The second and third parts of Pi/2 off `r = x - fn * pio2_1`, good to 118 and 151 bits.
214
+ fun trigReduce2(op: Int, n: Int, fn: Float, j: Int, r: Float) -> Float =
215
+ t := fn * 6.07710050630396597660e-11
216
+ r2 := r - t
217
+ w2 := fn * 2.02226624879595063154e-21 - {{r - r2} - t}
218
+ y2 := r2 - w2
219
+ if j - {{y2.toBits() >> 52} & 0x7FF} > 49
220
+ t3 := fn * 2.02226624871116645580e-21
221
+ r3 := r2 - t3
222
+ w3 := fn * 8.47842766036889956997e-32 - {{r2 - r3} - t3}
223
+ y3 := r3 - w3
224
+ trigAt(op, n, y3, {r3 - y3} - w3)
225
+ else
226
+ trigAt(op, n, y2, {r2 - y2} - w2)
227
+
228
+ # `op` (0 sin, 1 cos, 2 tan) of `n * Pi/2 + y0 + y1`: cos is sin a quadrant on.
229
+ fun trigAt(op: Int, n: Int, y0: Float, y1: Float) -> Float =
230
+ if op == 2
231
+ tanKernel(y0, y1, 1 - 2 * {n & 1})
232
+ else
233
+ q := {n + op} & 3
234
+ if q == 0
235
+ sinKernel(y0, y1)
236
+ else if q == 1
237
+ cosKernel(y0, y1)
238
+ else if q == 2
239
+ -sinKernel(y0, y1)
240
+ else
241
+ -cosKernel(y0, y1)
242
+
243
+ # `x mod Pi/2` for `|x| >= 2^20 * Pi/2`, finite (Payne and Hanek, in integers instead of
244
+ # fdlibm's `__kernel_rem_pio2`). `|x| = m * 2^e` with `m` 53 bits; the bits of 2/Pi past
245
+ # 2^(2 - e) only add multiples of 4 to `m * 2^e * 2/Pi`, so the product of `m` with the 240
246
+ # bits of 2/Pi from about there (ten 24-bit chunks) is taken exactly, as 13 limbs of 24
247
+ # bits. It has `s = 24 * (j0 + 10) - e` fraction bits, at least 215: bits `s` and `s + 1`
248
+ # are `n mod 4` and the top 160 fraction bits `f` (about 2^-160 off, against at least 2^-62,
249
+ # the closest any Float comes to a multiple of Pi/2). From `f >= 1/2` on, `f - 1` is taken
250
+ # (and `n + 1`); `f` times Pi/2, both as two doubles, is `y0 + y1`, negated for a negative `x`
251
+ # (with `-n`).
252
+ fun trigHuge(op: Int, x: Float) -> Float =
253
+ b := x.toBits()
254
+ m := {b & 0x000F_FFFF_FFFF_FFFF} | 0x0010_0000_0000_0000
255
+ e := {{b >> 52} & 0x7FF} - 1075
256
+ j0 := if e < 2 then 0 else {e - 2} / 24
257
+ p := Array.filled(13, 0)
258
+ trigLimbs(p, j0, m & 0xFF_FFFF, {m >> 24} & 0xFF_FFFF, m >> 48, 0, 0)
259
+ s := 24 * {j0 + 10} - e
260
+ f1 := limbBits(p, s - 40, 40)
261
+ up := f1 >> 39 == 1
262
+ # 1 - f, but for 2^-160, by the complement of the bits
263
+ g1 := if up then 0xFF_FFFF_FFFF - f1 else f1
264
+ g2 := if up then 0xFF_FFFF_FFFF - limbBits(p, s - 80, 40) else limbBits(p, s - 80, 40)
265
+ g3 := if up then 0xFF_FFFF_FFFF - limbBits(p, s - 120, 40) else limbBits(p, s - 120, 40)
266
+ g4 := if up then 0xFF_FFFF_FFFF - limbBits(p, s - 160, 40) else limbBits(p, s - 160, 40)
267
+ n := limbBits(p, s, 2) + {if up then 1 else 0}
268
+ # g = g1 2^-40 + g2 2^-80 + ... (each part exact) as hi + lo; hi has g1's bits, if any
269
+ d1 := Float(g1) * 9.094947017729282e-13
270
+ d2 := Float(g2) * 8.271806125530277e-25
271
+ hi := d1 + d2
272
+ lo := {d2 - {hi - d1}} + {Float(g3) * 7.52316384526264e-37 + Float(g4) * 6.842277657836021e-49}
273
+ gh := hi + lo
274
+ gl := lo - {gh - hi}
275
+ # (gh + gl) * (Pi/2 as ph + pl): gh * ph exactly (Dekker's product), the rest rounded
276
+ ph := 1.5707963267948966f
277
+ c := gh * 134217729.0f
278
+ ah := c - {c - gh}
279
+ al := gh - ah
280
+ bh := 1.5707963407039642f
281
+ bl := ph - bh
282
+ q := gh * ph
283
+ qe := {{{ah * bh - q} + ah * bl} + al * bh} + al * bl
284
+ tail := qe + {gh * 6.123233995736766e-17 + gl * ph}
285
+ y0 := q + tail
286
+ y1 := tail - {y0 - q}
287
+ # f - 1 is -(1 - f); and x's sign
288
+ k := if b < 0 then -n else n
289
+ if {b < 0} != up
290
+ trigAt(op, k, -y0, -y1)
291
+ else
292
+ trigAt(op, k, y0, y1)
293
+
294
+ # Limbs `q` up of `m * C` (`m = a2 * 2^48 + a1 * 2^24 + a0`, `C` the ten 24-bit chunks of
295
+ # 2/Pi from chunk `j0`, the first one highest) into `p`, `carry` in from limb `q - 1`.
296
+ fun trigLimbs(p: Array[Int], j0: Int, a0: Int, a1: Int, a2: Int, q: Int, carry: Int) -> Unit =
297
+ if q < 13
298
+ v := carry + a0 * chunkOf(j0, 9 - q) + a1 * chunkOf(j0, 10 - q) + a2 * chunkOf(j0, 11 - q)
299
+ p.set(q, v & 0xFF_FFFF)
300
+ trigLimbs(p, j0, a0, a1, a2, q + 1, v >> 24)
301
+
302
+ # Chunk `j0 + i` of 2/Pi, for `i` in 0..9, else 0.
303
+ fun chunkOf(j0: Int, i: Int) -> Int =
304
+ if i < 0 || i > 9 then 0 else twoOverPi(j0 + i)
305
+
306
+ # Bits `lo` to `lo + w - 1` (`w <= 40`) of the limbs.
307
+ fun limbBits(p: Array[Int], lo: Int, w: Int) -> Int =
308
+ q := lo / 24
309
+ o := lo % 24
310
+ v := {limbAt(p, q) >> o} | {limbAt(p, q + 1) << {24 - o}} | {limbAt(p, q + 2) << {48 - o}}
311
+ v & {{1 << w} - 1}
312
+
313
+ fun limbAt(p: Array[Int], q: Int) -> Int =
314
+ if q < 13 then p.get(q) else 0
315
+
316
+ # The bits of 2/Pi, 24 at a time: chunk `j` is bits `24j + 1` to `24j + 24` after the point
317
+ # (fdlibm's `ipio2`). Fifty cover `Float.Max`.
318
+ fun twoOverPi(j: Int) -> Int = match j
319
+ 0 => 0xA2F983
320
+ 1 => 0x6E4E44
321
+ 2 => 0x1529FC
322
+ 3 => 0x2757D1
323
+ 4 => 0xF534DD
324
+ 5 => 0xC0DB62
325
+ 6 => 0x95993C
326
+ 7 => 0x439041
327
+ 8 => 0xFE5163
328
+ 9 => 0xABDEBB
329
+ 10 => 0xC561B7
330
+ 11 => 0x246E3A
331
+ 12 => 0x424DD2
332
+ 13 => 0xE00649
333
+ 14 => 0x2EEA09
334
+ 15 => 0xD1921C
335
+ 16 => 0xFE1DEB
336
+ 17 => 0x1CB129
337
+ 18 => 0xA73EE8
338
+ 19 => 0x8235F5
339
+ 20 => 0x2EBB44
340
+ 21 => 0x84E99C
341
+ 22 => 0x7026B4
342
+ 23 => 0x5F7E41
343
+ 24 => 0x3991D6
344
+ 25 => 0x398353
345
+ 26 => 0x39F49C
346
+ 27 => 0x845F8B
347
+ 28 => 0xBDF928
348
+ 29 => 0x3B1FF8
349
+ 30 => 0x97FFDE
350
+ 31 => 0x05980F
351
+ 32 => 0xEF2F11
352
+ 33 => 0x8B5A0A
353
+ 34 => 0x6D1F6D
354
+ 35 => 0x367ECF
355
+ 36 => 0x27CB09
356
+ 37 => 0xB74F46
357
+ 38 => 0x3F669E
358
+ 39 => 0x5FEA2D
359
+ 40 => 0x7527BA
360
+ 41 => 0xC7EBE5
361
+ 42 => 0xF17B3D
362
+ 43 => 0x0739F7
363
+ 44 => 0x8A5292
364
+ 45 => 0xEA6BFB
365
+ 46 => 0x5FB11F
366
+ 47 => 0x8D5D08
367
+ 48 => 0x560330
368
+ _ => 0x46FC7B
369
+
370
+ # fdlibm's `__kernel_sin` (FreeBSD's `k_sin.c`) with no tail: sin(x) for |x| <= Pi/4, x plus
371
+ # x^3 times a degree-10 even polynomial.
372
+ fun sinKernel0(x: Float) -> Float =
373
+ z := x * x
374
+ w := z * z
375
+ r := 8.33333333332248946124e-03 + z * {-1.98412698298579493134e-04 + z * 2.75573137070700676789e-06} + z * w * {-2.50507602534068634195e-08 + z * 1.58969099521155010221e-10}
376
+ x + z * x * {-1.66666666666666324348e-01 + z * r}
377
+
378
+ # `__kernel_sin` with the tail `y` of the reduced argument: sin(x + y), `|y|` under half an ulp
379
+ # of `x`.
380
+ fun sinKernel(x: Float, y: Float) -> Float =
381
+ z := x * x
382
+ w := z * z
383
+ r := 8.33333333332248946124e-03 + z * {-1.98412698298579493134e-04 + z * 2.75573137070700676789e-06} + z * w * {-2.50507602534068634195e-08 + z * 1.58969099521155010221e-10}
384
+ v := z * x
385
+ x - {{z * {0.5f * y - v * r} - y} - v * -1.66666666666666324348e-01}
386
+
387
+ # fdlibm's `__kernel_cos` (FreeBSD's `k_cos.c`): cos(x + y) for |x| <= Pi/4, 1 - x^2/2 (with
388
+ # what that subtraction rounds off kept) plus x^4 times a degree-10 even polynomial.
389
+ fun cosKernel(x: Float, y: Float) -> Float =
390
+ z := x * x
391
+ w := z * z
392
+ r := z * {4.16666666666666019037e-02 + z * {-1.38888888888741095749e-03 + z * 2.48015872894767294178e-05}} + w * w * {-2.75573143513906633035e-07 + z * {2.08757232129817482790e-09 + z * -1.13596475577881948265e-11}}
393
+ hz := 0.5f * z
394
+ v := 1.0f - hz
395
+ v + {{{1.0f - v} - hz} + {z * r - x * y}}
396
+
397
+ # fdlibm's `__kernel_tan` (FreeBSD's `k_tan.c`): tan(x + y) for `iy` 1, -1/tan(x + y) for
398
+ # `iy` -1, |x| <= Pi/4. From |x| = 0.6744 up it works on Pi/4 - |x| instead and turns the
399
+ # result back with tan(Pi/4 - t) = (1 - tan t) / (1 + tan t).
400
+ fun tanKernel(x: Float, y: Float, iy: Int) -> Float =
401
+ if {x.toBits() & 0x7FFF_FFFF_FFFF_FFFF} >> 32 >= 0x3FE5_9428
402
+ neg := x < 0.0f
403
+ t := {7.85398163397448278999e-01 - {if neg then -x else x}} + {3.06161699786838301793e-17 - {if neg then -y else y}}
404
+ v := Float(iy)
405
+ s := tanPoly(t, 0.0f)
406
+ w := t + s
407
+ a := v - 2.0f * {t - {w * w / {w + v} - s}}
408
+ if neg then -a else a
409
+ else
410
+ s := tanPoly(x, y)
411
+ w := x + s
412
+ if iy == 1
413
+ w
414
+ else
415
+ # -1/(x + s), to under an ulp: the division's error taken back with the high halves
416
+ z := Float.fromBits(w.toBits() & -0x1_0000_0000)
417
+ v := s - {z - x}
418
+ a := -1.0f / w
419
+ t := Float.fromBits(a.toBits() & -0x1_0000_0000)
420
+ t + a * {{1.0f + t * z} + t * v}
421
+
422
+ # `tan(x + y) - x`: x^3 times fdlibm's degree-24 even polynomial (split into two chains in
423
+ # x^4), plus `y` and its first-order term.
424
+ fun tanPoly(x: Float, y: Float) -> Float =
425
+ z := x * x
426
+ w := z * z
427
+ r := 1.33333333333201242699e-01 + w * {2.18694882948595424599e-02 + w * {3.59207910759131235356e-03 + w * {5.88041240820264096874e-04 + w * {7.81794442939557092300e-05 + w * -1.85586374855275456654e-05}}}}
428
+ v := z * {5.39682539762260521377e-02 + w * {8.86323982359930005737e-03 + w * {1.45620945432529025516e-03 + w * {2.46463134818469906812e-04 + w * {7.14072491382608190305e-05 + w * 2.59073051863633712884e-05}}}}}
429
+ s := z * x
430
+ {y + z * {s * {r + v} + y}} + 3.33333333333334091986e-01 * s
198
431
 
199
432
  # Arctangent, fdlibm's `s_atan.c` (under 1 ulp): `|x|` is reduced by the breakpoints 7/16,
200
433
  # 11/16, 19/16 and 39/16 to `|t| <= 7/16` around one of atan(0.5), atan(1), atan(1.5) and
tests/core/float_bits.plum CHANGED
@@ -1,7 +1,8 @@
1
1
  # `Float.toBits` / `Float.fromBits` (wasm's `i64.reinterpret_f64` / `f64.reinterpret_i64`),
2
- # and std math's unrolled series (sin, cos, tan, exp, ln), fdlibm's atan and bit-read range reduction
2
+ # std math's unrolled series (exp, ln) and bit-read range reduction (exp, ln): the expected bits
3
- # (exp, ln): the expected bits are the ones the loop versions gave (see
4
- # benchmarks/math_bits/check.plum, which compares the two over millions of inputs).
3
+ # are the ones the loop versions gave (see benchmarks/math_bits/check.plum, which compares the
4
+ # two over millions of inputs); and fdlibm's sin, cos, tan and atan, whose bits were checked
5
+ # against mpmath.
5
6
  import std/Float
6
7
  import std/Int
7
8
  import std/math
@@ -70,18 +71,20 @@ test "toBits and fromBits in closures"
70
71
  assert applyF(|b| Float.fromBits(b), 0x7FF8_0000_DEAD_BEEF).toBits() == 0x7FF8_0000_DEAD_BEEF
71
72
 
72
73
  test "sin, cos and tan keep their bits"
74
+ # fdlibm's: the nearest float but for sin(-2.5), the other neighbour (0.503 ulp off)
73
75
  assert posZero(math.sin(0.0f))
74
76
  assert negZero(math.sin(-0.0f))
75
77
  assert math.sin(1.0f).toBits() == 4605754516372524270
76
- assert math.sin(-2.5f).toBits() == -4619806259459182587
78
+ assert math.sin(-2.5f).toBits() == -4619806259459142992
77
- assert math.sin(Float.Pi).toBits() == 4468182615269985440
79
+ assert math.sin(Float.Pi).toBits() == 4368955796522032135
78
- assert math.sin(1.0e6).toBits() == -4623395494514420638
80
+ assert math.sin(1.0e6).toBits() == -4623395494513026969
81
+ assert math.sin(1.0e22).toBits() == -4617520874450586729
79
82
  assert math.sin(Float.Min) == Float.Min
80
83
  assert math.cos(0.0f) == 1.0f
81
- assert math.cos(1.0f).toBits() == 4603041830071955640
84
+ assert math.cos(1.0f).toBits() == 4603041830072026764
82
- assert math.cos(-3.0f).toBits() == -4616279757631920688
85
+ assert math.cos(-3.0f).toBits() == -4616279757631920686
83
- assert math.tan(0.5f).toBits() == 4603095874924661028
86
+ assert math.tan(0.5f).toBits() == 4603095874924660554
84
- assert math.tan(-1.25f).toBits() == -4609412669623881302
87
+ assert math.tan(-1.25f).toBits() == -4609412669623881304
85
88
  assert math.sin(NaN).isNaN()
86
89
  assert math.sin(Inf).isNaN()
87
90
  assert math.cos(-Inf).isNaN()
tests/core/math_edges.plum CHANGED
@@ -1,6 +1,7 @@
1
1
  # std math at its edges: `Float.logb` read from the bits, `math.cbrt` from a bit-level guess
2
2
  # (correctly rounded), `math.atan` (fdlibm's, under 1 ulp) across its breakpoints, past 2^60
3
+ # and at the infinities, `sin`, `cos` and `tan` (fdlibm's) at multiples of Pi/2, for huge
3
- # and at the infinities, `asin` and `acos` near the ends, the sign of zero through `sin`,
4
+ # arguments and at subnormals, `asin` and `acos` near the ends, the sign of zero through `sin`,
4
5
  # `atan` and `atan2` (C99's cases), `atan2` with NaNs and infinities, `Int.Min.toStr()`,
5
6
  # `Float.toStr` past Int's range, and `Float.hash` on the bits. Expected roots and angles are
6
7
  # the correctly rounded doubles (checked against mpmath at 300 bits).
@@ -94,6 +95,91 @@ test "sin, tan and atan keep the sign of zero"
94
95
  assert posZero(math.atan(0.0f))
95
96
  assert math.cos(-0.0f) == 1.0f
96
97
 
98
+ test "sin, cos and tan to the nearest float at and next to multiples of Pi/2"
99
+ # the correctly rounded values (mpmath, 300 bits); the old series was up to 10^22 ulp off here
100
+ assert math.sin(Float.Pi) == 1.2246467991473532e-16
101
+ assert math.cos(Float.Pi) == -1.0f
102
+ assert math.tan(Float.Pi) == -1.2246467991473532e-16
103
+ assert math.sin(-Float.Pi) == -1.2246467991473532e-16
104
+ assert math.cos(-Float.Pi) == -1.0f
105
+ assert math.tan(-Float.Pi) == 1.2246467991473532e-16
106
+ assert math.sin(Float.HalfPi) == 1.0f
107
+ assert math.cos(Float.HalfPi) == 6.123233995736766e-17
108
+ assert math.tan(Float.HalfPi) == 1.633123935319537e16
109
+ assert math.sin(Float.Tau) == -2.4492935982947064e-16
110
+ assert math.cos(Float.Tau) == 1.0f
111
+ assert math.tan(Float.Tau) == -2.4492935982947064e-16
112
+ assert math.sin(3.0f * Float.HalfPi) == -1.0f
113
+ assert math.cos(3.0f * Float.HalfPi) == -1.8369701987210297e-16
114
+ assert math.tan(3.0f * Float.HalfPi) == 5443746451065123.0f
115
+ assert math.sin(100.0f) == -0.5063656411097588
116
+ assert math.cos(100.0f) == 0.8623188722876839
117
+ assert math.tan(100.0f) == -0.5872139151569291
118
+ assert math.sin(-91.106186954104) == 1.2379612731767154e-18
119
+ assert math.cos(-91.106186954104) == -1.0f
120
+ assert math.tan(-91.106186954104) == -1.2379612731767154e-18
121
+ assert math.sin(45.553093477052) == 1.0f
122
+ assert math.cos(45.553093477052) == -6.189806365883577e-19
123
+ assert math.tan(45.553093477052) == -1.6155594228467482e18
124
+ assert math.sin(0.7853981633974483f) == 0.7071067811865475
125
+ assert math.cos(0.7853981633974483f) == 0.7071067811865476
126
+ assert math.tan(0.7853981633974483f) == 0.9999999999999999
127
+ assert math.sin(1.5707963267948963) == 1.0f
128
+ assert math.cos(1.5707963267948963) == 2.83276944882399e-16
129
+ assert math.tan(1.5707963267948963) == 3530114321217157.5
130
+ assert math.sin(1.0e-8) == 1.0e-8
131
+ assert math.cos(1.0e-8) == 1.0f
132
+ assert math.tan(1.0e-8) == 1.0e-8
133
+ assert math.sin(3.0e-300) == 3.0e-300
134
+ assert math.cos(3.0e-300) == 1.0f
135
+ assert math.tan(3.0e-300) == 3.0e-300
136
+
137
+ test "sin, cos and tan of huge arguments, reduced by 2/Pi's bits"
138
+ # past 2^20 * Pi/2 (1647099.33) the reduction multiplies by 2/Pi in integers; the worst
139
+ # case is 6381956970095103 * 2^797, 4.7e-19 from a multiple of Pi/2
140
+ assert math.sin(1.0e22) == -0.8522008497671888
141
+ assert math.cos(1.0e22) == 0.523214785395139
142
+ assert math.sin(-1.0e22) == 0.8522008497671888
143
+ assert math.cos(-1.0e22) == 0.523214785395139
144
+ assert math.sin(Float.Max) == 0.004961954789184062
145
+ assert math.cos(Float.Max) == -0.9999876894265599
146
+ assert math.tan(Float.Max) == -0.004962015874444895
147
+ assert math.sin(6381956970095103.0f * Float.fromBits({1023 + 797} << 52)) == 1.0f
148
+ assert math.cos(6381956970095103.0f * Float.fromBits({1023 + 797} << 52)) == -4.687165924254628e-19
149
+ assert math.tan(6381956970095103.0f * Float.fromBits({1023 + 797} << 52)) == -2.133485385753704e18
150
+ assert math.sin(Float.fromBits({1023 + 1000} << 52)) == -0.15920170308624243
151
+ assert math.cos(Float.fromBits({1023 + 1000} << 52)) == 0.9872460775989135
152
+ assert math.tan(Float.fromBits({1023 + 1000} << 52)) == -0.16125837995065806
153
+ assert math.sin(1.0e6) == -0.34999350217129294
154
+ assert math.cos(1.0e6) == 0.9367521275331447
155
+ assert math.tan(1.0e6) == -0.373624453987599
156
+ assert math.sin(1647099.3291652855) == -6.420676210313675e-11
157
+ assert math.cos(1647099.3291652855) == 1.0f
158
+ assert math.tan(1647099.3291652855) == -6.420676210313675e-11
159
+ assert math.sin(1647099.329165286) == 4.014545252046025e-10
160
+ assert math.cos(1647099.329165286) == 1.0f
161
+ assert math.tan(1647099.329165286) == 4.014545252046025e-10
162
+ # 0.544 ulp off, the other neighbour (the nearest float is -1.6287782256068988)
163
+ assert {math.tan(1.0e22) - -1.6287782256068988}.abs() <= 2.220446049250313e-16
164
+ assert {math.tan(-1.0e22) - 1.6287782256068988}.abs() <= 2.220446049250313e-16
165
+
166
+ test "sin, cos and tan of subnormals, infinities and NaN"
167
+ assert math.sin(Float.Min) == Float.Min
168
+ assert math.sin(-Float.Min) == -Float.Min
169
+ assert math.tan(-Float.Min) == -Float.Min
170
+ assert math.cos(Float.Min) == 1.0f
171
+ assert math.sin(Float.fromBits(0x000F_FFFF_FFFF_FFFF)) == Float.fromBits(0x000F_FFFF_FFFF_FFFF)
172
+ assert math.cos(1.0e-8) == 1.0f
173
+ assert math.sin(Inf).isNaN()
174
+ assert math.sin(-Inf).isNaN()
175
+ assert math.cos(Inf).isNaN()
176
+ assert math.cos(-Inf).isNaN()
177
+ assert math.tan(Inf).isNaN()
178
+ assert math.tan(-Inf).isNaN()
179
+ assert math.sin(NaN).isNaN()
180
+ assert math.cos(NaN).isNaN()
181
+ assert math.tan(NaN).isNaN()
182
+
97
183
  test "atan2 with huge ratios, NaNs and infinities"
98
184
  assert math.atan2(1.0e300, 1.0e-10) == Float.HalfPi
99
185
  assert math.atan2(-1.0e300, 1.0e-10) == -Float.HalfPi