plum

#treesitter#compiler#wasm

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

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


0249865 — Peter John 2026-11-10T11:02:50+05:30
std math: fdlibm atan and atan2 (C99 signed zeros), correctly rounded cbrt, asin/acos without cancellation
benchmarks/math_bits/check.plum CHANGED
@@ -1,9 +1,10 @@
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 fixes made since (`sin` and `atan` keep a zero's sign,
4
+ # sign of zero included). The edge fix made since (`sin` keeps a zero's sign) is copied into
5
+ # the old version too, so only the unrolling is compared. `atan` is no longer compared: it is
5
- # `atan` past 2^60 is `Pi/2 - atan(1/|x|)`) are copied into the old versions too, so only the
6
+ # now fdlibm's (under 1 ulp; the old series was up to 165 ulp off) and was checked against
6
- # unrolling is compared. `logb` now reads the exponent from the bits; it is checked against an
7
+ # mpmath instead. `logb` now reads the exponent from the bits; it is checked against an
7
8
  # exact halve-or-double reference instead (the old `floor(ln(|x|) * Log2E)` was wrong for
8
9
  # about 40% of the floats just below a power of two).
9
10
  #
@@ -118,30 +119,6 @@ fun oldCos(x: Float) -> Float =
118
119
  fun oldTan(x: Float) -> Float =
119
120
  oldSin(x) / oldCos(x)
120
121
 
121
- fun oldAtan(x: Float) -> Float =
122
- if x != x || x == 0.0f
123
- x
124
- else
125
- neg := x < 0.0f
126
- v := if neg then -x else x
127
- result := if v > 1152921504606846976.0f then Float.HalfPi - oldAtanReduce(1.0f / v, 0) else oldAtanReduce(v, 0)
128
- if neg then -result else result
129
-
130
- fun oldAtanReduce(v: Float, k: Int) -> Float =
131
- if v > 0.5f && k < 8
132
- oldAtanReduce(v / {1.0f + math.sqrt(1.0f + v * v)}, k + 1)
133
- else
134
- sum := oldAtanSeries(v * v, v, v, 1)
135
- scale := Float(1 << k)
136
- sum * scale
137
-
138
- fun oldAtanSeries(v2: Float, term: Float, sum: Float, n: Int) -> Float =
139
- if n < 20
140
- t := term * {-v2}
141
- oldAtanSeries(v2, t, sum + t / Float(2 * n + 1), n + 1)
142
- else
143
- sum
144
-
145
122
  fun oldPow(base: Float, y: Float) -> Float =
146
123
  if y == 0.0f
147
124
  1.0f
@@ -327,7 +304,6 @@ fun main(io: Io) =
327
304
  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))
328
305
  b6 := report(io, "ln", n, sweep1(io, |x| oldLn(x), |x| math.ln(x), 0, n, 0))
329
306
  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))
330
- b8 := report(io, "atan", n, sweep1(io, |x| oldAtan(x), |x| math.atan(x), 0, n, 0))
331
307
  b9 := report(io, "logb (against an exact reference)", n, sweep1(io, |x| refLogb(x), |x| x.logb(), 0, n, 0))
332
308
  b10 := report(io, "pow", n, sweep2(io, |x, y| oldPow(x, y), |x, y| x.pow(y), 0, n, 0))
333
- io.printLn("mismatches {b1 + b2 + b3 + b4 + b5 + b6 + b7 + b8 + b9 + b10}")
309
+ io.printLn("mismatches {b1 + b2 + b3 + 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", "atanSeries"] {
156
+ for s in ["sinSeries", "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
@@ -40,7 +40,7 @@ fun main() =
40
40
 
41
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.
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` starts from a guess read from the bits (the exponent divided by 3) and is faithfully rounded, under 0.667 ulp, for every Float, subnormals and `1e300` included (`cbrt(1e300)` is `1e100`); it keeps the sign (`cbrt(-0.0)` is `-0.0`), and NaN and the infinities pass through. `math.atan` past 2^60 is `Pi/2 - atan(1/|x|)` with the sign of `x`, so `atan(1e300)` and `atan(Infinity)` are `Pi/2`. `sin(-0.0)`, `tan(-0.0)` and `atan(-0.0)` are `-0.0`. `math.atan2` gives NaN for a NaN on either side, and `±Pi/4` or `±3*Pi/4` when both sides are infinite.
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`.
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
@@ -196,51 +196,49 @@ fun cos(x: Float) -> Float =
196
196
  fun tan(x: Float) -> Float =
197
197
  sin(x) / cos(x)
198
198
 
199
- # Arctangent, via repeated argument-halving (`atan(x) = 2*atan(x / (1 +
199
+ # Arctangent, fdlibm's `s_atan.c` (under 1 ulp): `|x|` is reduced by the breakpoints 7/16,
200
- # sqrt(1+x^2)))`) until `|x| <= 0.5` (where the Taylor series below converges
200
+ # 11/16, 19/16 and 39/16 to `|t| <= 7/16` around one of atan(0.5), atan(1), atan(1.5) and
201
- # quickly), then doubling the result back up the same number of times. Past 2^60 (where
201
+ # atan(Infinity) = Pi/2 (each kept as a high and a low double), then atan(t) is t minus t
202
- # `x * x` would overflow before long) it is `Pi/2 - atan(1/|x|)` with the sign of `x`, so
202
+ # times an odd polynomial of degree 22 in t. The breakpoints are compared on the high 32 bits,
203
- # `atan(Infinity)` is `Pi/2`; `atan(-0.0)` is `-0.0`.
203
+ # as in fdlibm, so the results are fdlibm's bit for bit. Below 2^-27 `atan(x)` is `x` (the
204
+ # sign of a zero kept); from 2^66 up, and at the infinities, it is `±Pi/2`.
204
205
  fun atan(x: Float) -> Float =
206
+ a := x.toBits() & 0x7FFF_FFFF_FFFF_FFFF
207
+ h := a >> 32
205
- if x != x || x == 0.0f
208
+ if x != x
206
209
  x
210
+ else if h >= 0x4410_0000
211
+ if x < 0.0f then -Float.HalfPi else Float.HalfPi
212
+ else if h < 0x3FDC_0000
213
+ if h < 0x3E40_0000 then x else x - x * atanPoly(x * x)
207
214
  else
215
+ v := Float.fromBits(a)
208
- neg := x < 0.0f
216
+ r := if h < 0x3FE6_0000
217
+ atanNear(4.63647609000806093515e-01, 2.26987774529616870924e-17, {2.0f * v - 1.0f} / {2.0f + v})
218
+ else if h < 0x3FF3_0000
219
+ atanNear(7.85398163397448278999e-01, 3.06161699786838301793e-17, {v - 1.0f} / {v + 1.0f})
220
+ else if h < 0x4003_8000
221
+ atanNear(9.82793723247329054082e-01, 1.39033110312309984516e-17, {v - 1.5f} / {1.0f + 1.5f * v})
222
+ else
223
+ atanNear(1.57079632679489655800e+00, 6.12323399573676603587e-17, -1.0f / v)
209
- v := if neg then -x else x
224
+ if x < 0.0f then -r else r
210
- result := if v > 1152921504606846976.0f then Float.HalfPi - atanReduce(1.0f / v, 0) else atanReduce(v, 0)
211
- if neg then -result else result
212
225
 
226
+ # atan(c) + atan(t), atan(c) given as `hi + lo`.
213
- fun atanReduce(v: Float, k: Int) -> Float =
227
+ fun atanNear(hi: Float, lo: Float, t: Float) -> Float =
214
- if v > 0.5f && k < 8
215
- atanReduce(v / {1.0f + sqrt(1.0f + v * v)}, k + 1)
216
- else
217
- sum := atanSeries(v, -{v * v})
228
+ hi - {{t * atanPoly(t * t) - lo} - t}
218
- scale := Float(1 << k)
219
- sum * scale
220
229
 
221
- # v - v^3/3 + v^5/5 - ... - v^39/39, in order: each power is the one before times -v^2.
222
- fun atanSeries(v: Float, m: Float) -> Float =
223
- p3 := v * m
224
- p5 := p3 * m
225
- p7 := p5 * m
226
- p9 := p7 * m
227
- p11 := p9 * m
228
- p13 := p11 * m
229
- p15 := p13 * m
230
- p17 := p15 * m
231
- p19 := p17 * m
232
- p21 := p19 * m
233
- p23 := p21 * m
234
- p25 := p23 * m
235
- p27 := p25 * m
236
- p29 := p27 * m
237
- p31 := p29 * m
238
- p33 := p31 * m
239
- p35 := p33 * m
240
- p37 := p35 * m
241
- p39 := p37 * m
242
- v + p3 / 3.0f + p5 / 5.0f + p7 / 7.0f + p9 / 9.0f + p11 / 11.0f + p13 / 13.0f + p15 / 15.0f + p17 / 17.0f + p19 / 19.0f + p21 / 21.0f + p23 / 23.0f + p25 / 25.0f + p27 / 27.0f + p29 / 29.0f + p31 / 31.0f + p33 / 33.0f + p35 / 35.0f + p37 / 37.0f + p39 / 39.0f
230
+ # fdlibm's odd polynomial for atan(t) = t - t * atanPoly(t^2), |t| <= 7/16, split into the even
231
+ # and odd powers of z = t^2 (two Horner chains in w = z^2) as fdlibm has it.
232
+ fun atanPoly(z: Float) -> Float =
233
+ w := z * z
234
+ s1 := z * {3.33333333333329318027e-01 + w * {1.42857142725034663711e-01 + w * {9.09088713343650656196e-02 + w * {6.66107313738753120669e-02 + w * {4.97687799461593236017e-02 + w * 1.62858201153657823623e-02}}}}}
235
+ s2 := w * {-1.99999999998764832476e-01 + w * {-1.11111104054623557880e-01 + w * {-7.69187620504482999495e-02 + w * {-5.83357013379057348645e-02 + w * {-3.65315727442169155270e-02}}}}}
236
+ s1 + s2
243
237
 
238
+ # Arcsine, `atan(x / sqrt(1 - x * x))`, from `|x| = 0.5` up with `(1 - x) * (1 + x)` for
239
+ # `1 - x * x` (`1 - x` is exact there, so the digits `1 - x * x` loses near `±1` are kept),
240
+ # and `x` itself below 2^-26: within 1.5 ulp. `asin(±1)` is `±Pi/2`, `asin(-0.0)` is
241
+ # `-0.0`, and outside [-1, 1] or for NaN it is NaN.
244
242
  fun asin(x: Float) -> Float =
245
243
  if x != x || x < -1.0f || x > 1.0f
246
244
  0.0f / 0.0f
@@ -248,34 +246,71 @@ fun asin(x: Float) -> Float =
248
246
  Float.HalfPi
249
247
  else if x == -1.0f
250
248
  -Float.HalfPi
249
+ else if x < 1.4901161193847656e-08 && x > -1.4901161193847656e-08
250
+ # below 2^-26 asin(x) = x + x^3/6 + ... rounds to x
251
- else
251
+ x
252
+ else if x < 0.5f && x > -0.5f
252
253
  atan(x / sqrt(1.0f - x * x))
254
+ else
255
+ atan(x / sqrt({1.0f - x} * {1.0f + x}))
253
256
 
257
+ # Arccosine, `2 * atan(sqrt((1 - x) / (1 + x)))`, within about 1.5 ulp (`Pi/2 - asin(x)` loses
258
+ # digits to cancellation near 1). `acos(1)` is `0.0`, `acos(-1)` is `Pi`, and outside
259
+ # [-1, 1] or for NaN it is NaN.
254
260
  fun acos(x: Float) -> Float =
261
+ if x != x || x < -1.0f || x > 1.0f
255
- Float.HalfPi - asin(x)
262
+ 0.0f / 0.0f
263
+ else
264
+ 2.0f * atan(sqrt({1.0f - x} / {1.0f + x}))
256
265
 
257
- # Angle (in radians) of the point `(x, y)` from the origin, in the correct
266
+ # Angle (in radians) of the point `(x, y)` from the origin, in (-Pi, Pi], in the correct
258
- # quadrant for any sign combination of `x`/`y` (unlike plain `atan(y/x)`,
267
+ # quadrant for any sign combination of `x`/`y` (unlike plain `atan(y/x)`, which can't
259
- # which can't distinguish opposite quadrants). A NaN gives NaN; both sides infinite give
268
+ # distinguish opposite quadrants). fdlibm's `e_atan2.c`, under 2 ulp, with C99's special
269
+ # cases: a NaN gives NaN; `atan2(±0, x)` is `±0` for `x` above zero or `+0`, `±Pi` for `x`
270
+ # below zero or `-0`; `atan2(y, ±0)` for a nonzero `y` is `±Pi/2` by the sign of `y`; an
271
+ # infinite `x` gives `±0` (`x` positive) or `±Pi` (negative) for a finite `y`, and `±Pi/4` or
260
- # `±Pi/4` or `±3*Pi/4`.
272
+ # `±3*Pi/4` for an infinite one; an infinite `y` with a finite `x` gives `±Pi/2`.
261
273
  fun atan2(y: Float, x: Float) -> Float =
274
+ yb := y.toBits()
275
+ xb := x.toBits()
276
+ # bit 0: y is negative, bit 1: x is negative (zeros and NaNs included)
277
+ m := {if yb < 0 then 1 else 0} + {if xb < 0 then 2 else 0}
278
+ ya := yb & 0x7FFF_FFFF_FFFF_FFFF
279
+ xa := xb & 0x7FFF_FFFF_FFFF_FFFF
262
280
  if x != x || y != y
263
281
  x + y
282
+ else if ya == 0
264
- else if {x > Float.Max || x < -Float.Max} && {y > Float.Max || y < -Float.Max}
283
+ if m < 2 then y else if m == 2 then Float.Pi else -Float.Pi
284
+ else if xa == 0
285
+ if m % 2 == 1 then -Float.HalfPi else Float.HalfPi
286
+ else if xa == 0x7FF0_0000_0000_0000
287
+ if ya == 0x7FF0_0000_0000_0000
265
- q := if x > 0.0f then 0.7853981633974483f else 2.356194490192345f
288
+ atan2Quadrant(m, 0.7853981633974483f, 2.356194490192345f)
266
- if y > 0.0f then q else -q
267
- else if x > 0.0f
289
+ else
268
- atan(y / x)
269
- else if x < 0.0f && y >= 0.0f
270
- atan(y / x) + Float.Pi
290
+ atan2Quadrant(m, 0.0f, Float.Pi)
271
- else if x < 0.0f && y < 0.0f
272
- atan(y / x) - Float.Pi
273
- else if x == 0.0f && y > 0.0f
291
+ else if ya == 0x7FF0_0000_0000_0000
274
- Float.HalfPi
275
- else if x == 0.0f && y < 0.0f
292
+ if m % 2 == 1 then -Float.HalfPi else Float.HalfPi
276
- -Float.HalfPi
277
293
  else
294
+ # the difference of the exponents (on the high words, as fdlibm)
295
+ k := {{ya >> 32} - {xa >> 32}} >> 20
296
+ if k > 60
297
+ # |y/x| > 2^60
298
+ z := Float.HalfPi + 0.5f * 1.2246467991473531772e-16
299
+ if m % 2 == 1 then -z else z
278
- 0.0f
300
+ else
301
+ z := if m >= 2 && k < -60 then 0.0f else atan({y / x}.abs())
302
+ if m == 0
303
+ z
304
+ else if m == 1
305
+ -z
306
+ else if m == 2
307
+ Float.Pi - {z - 1.2246467991473531772e-16}
308
+ else
309
+ {z - 1.2246467991473531772e-16} - Float.Pi
310
+
311
+ # `a` in the quadrant of `m` (`atan2`'s sign bits) with x positive, `b` with x negative.
312
+ fun atan2Quadrant(m: Int, a: Float, b: Float) -> Float =
313
+ if m == 0 then a else if m == 1 then -a else if m == 2 then b else -b
279
314
 
280
315
  # sqrt(a^2 + b^2), without overflow or underflow on the way: exactly `sqrt(a * a + b * b)`
281
316
  # when that sum is a finite number above 2^-968 (so every term that counts in it is a normal
@@ -302,25 +337,43 @@ fun hypotScaled(x: Float, y: Float) -> Float =
302
337
  r := small / big
303
338
  big * sqrt(1.0f + r * r)
304
339
 
305
- # Cube root, faithfully rounded (under 0.667 ulp of the true root, the method of FreeBSD's
340
+ # Cube root, correctly rounded but for a root within about 2^-22 ulp of halfway between two
306
- # `s_cbrt.c`): a first guess from the bits (the exponent divided by 3), a polynomial step to
341
+ # floats (none in a million sampled inputs over every exponent; the old faithful version
307
- # 23 bits, rounded to 23 bits so it cubes exactly, then one Newton step to 53 bits. A
342
+ # missed 7.9%). `|x|` is split into `m * 2^(3k)` with `m` in [1, 8), read from the bits (a
308
- # subnormal is first scaled by 2^54 (exact), its root then by 2^-18. The sign is kept:
343
+ # subnormal is first scaled by 2^54, exact), and the root of `m` times 2^k is the answer,
309
- # `cbrt(-8.0)` is `-2.0`, `cbrt(-0.0)` is `-0.0`; NaN and the infinities pass through.
344
+ # exactly. The sign is kept: `cbrt(-8.0)` is `-2.0`, `cbrt(-0.0)` is `-0.0`; NaN and the
345
+ # infinities pass through.
310
346
  fun cbrt(x: Float) -> Float =
311
347
  if x == 0.0f || x != x || x > Float.Max || x < -Float.Max
312
348
  x
313
349
  else
314
350
  b := x.toBits()
315
- a := b & 0x7FFF_FFFF_FFFF_FFFF
351
+ a0 := b & 0x7FFF_FFFF_FFFF_FFFF
352
+ sub := {a0 >> 52} == 0
316
- r := if {a >> 52} == 0 then cbrtNormal(Float.fromBits(a) * 18014398509481984.0f) * 0.000003814697265625f else cbrtNormal(Float.fromBits(a))
353
+ a := if sub then {Float.fromBits(a0) * 18014398509481984.0f}.toBits() else a0
354
+ e := {a >> 52} - {if sub then 1077 else 1023}
355
+ # k = floor(e / 3), from a positive dividend
356
+ k := {e + 1077} / 3 - 359
357
+ m := Float.fromBits({a & 0x000F_FFFF_FFFF_FFFF} | {{1023 + e - 3 * k} << 52})
358
+ r := cbrtRoot(m) * Float.fromBits({1023 + k} << 52)
317
359
  Float.fromBits(r.toBits() | {b & Int.Min})
318
360
 
319
- # The cube root of a positive normal float `v`.
361
+ # The cube root of `m` in [1, 8), to the nearest float. A first guess from the bits and a
362
+ # polynomial step to 23 bits (FreeBSD's `s_cbrt.c`), rounded to 23 bits so `t * t` is exact;
363
+ # then `t^3` exactly as `q + qe` (Dekker's product, `t * t` split into 26-bit halves), the
364
+ # residual `m - t^3` (one rounding: `m - q` is exact) and `u = (m - t^3) / t^3` (about
365
+ # 2^-22), and the root is `t * (1 + u)^(1/3)`, the binomial series to u^4 (the u^5 term is
366
+ # under 2^-110). The correction `t * (u/3 - u^2/9 + ...)` is about 2^-23 t, so its rounding
367
+ # errors are about 2^-22 ulp, and `t` plus it rounds to the nearest float.
320
- fun cbrtNormal(v: Float) -> Float =
368
+ fun cbrtRoot(m: Float) -> Float =
321
- t0 := Float.fromBits({{v.toBits() >> 32} / 3 + 715094163} << 32)
369
+ t0 := Float.fromBits({{m.toBits() >> 32} / 3 + 715094163} << 32)
322
- r := t0 * t0 * {t0 / v}
370
+ r := t0 * t0 * {t0 / m}
323
371
  t1 := t0 * {{1.87595182427177009643f + r * {-1.88497979543377169875f + r * 1.621429720105354466140f}} + r * r * r * {-0.758397934778766047437f + r * 0.145996192886612446982f}}
324
372
  t := Float.fromBits({t1.toBits() + 0x8000_0000} & -0x4000_0000)
373
+ p := t * t
374
+ q := p * t
375
+ ph := p * 134217729.0f - {p * 134217729.0f - p}
376
+ pl := p - ph
325
- q := v / {t * t}
377
+ qe := {ph * t - q} + pl * t
326
- t + t * {{q - t} / {t + t + q}}
378
+ u := {{m - q} - qe} / q
379
+ t + t * {u * {0.3333333333333333f + u * {-0.1111111111111111f + u * {0.06172839506172839f + u * {-0.0411522633744856f}}}}}
tests/core/float_bits.plum CHANGED
@@ -1,5 +1,5 @@
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, atan) and bit-read range reduction
2
+ # and std math's unrolled series (sin, cos, tan, exp, ln), fdlibm's atan and bit-read range reduction
3
3
  # (exp, ln): the expected bits are the ones the loop versions gave (see
4
4
  # benchmarks/math_bits/check.plum, which compares the two over millions of inputs).
5
5
  import std/Float
@@ -121,9 +121,9 @@ test "ln keeps its bits, for subnormals too"
121
121
 
122
122
  test "atan and pow keep their bits"
123
123
  assert posZero(math.atan(0.0f))
124
- assert math.atan(0.5f).toBits() == 4602023952714414762
124
+ assert math.atan(0.5f).toBits() == 4602023952714414927
125
125
  assert math.atan(1.0f).toBits() == 4605249457297304856
126
- assert math.atan(-7.0f).toBits() == -4614258027452340741
126
+ assert math.atan(-7.0f).toBits() == -4614258027452340739
127
127
  assert math.atan(NaN).isNaN()
128
128
  assert 2.0.pow(0.5f).toBits() == 4609047870845172686
129
129
  assert 10.0.pow(-1.5f).toBits() == 4584718143433226873
tests/core/math_edges.plum CHANGED
@@ -1,8 +1,9 @@
1
1
  # std math at its edges: `Float.logb` read from the bits, `math.cbrt` from a bit-level guess
2
+ # (correctly rounded), `math.atan` (fdlibm's, under 1 ulp) across its breakpoints, past 2^60
2
- # (faithfully rounded), `math.atan` past 2^60 and at the infinities, the sign of zero through
3
+ # and at the infinities, `asin` and `acos` near the ends, the sign of zero through `sin`,
3
- # `sin` and `atan`, `atan2` with NaNs and infinities, `Int.Min.toStr()`, `Float.toStr` past
4
+ # `atan` and `atan2` (C99's cases), `atan2` with NaNs and infinities, `Int.Min.toStr()`,
4
- # Int's range, and `Float.hash` on the bits. Expected roots and angles are the correctly
5
+ # `Float.toStr` past Int's range, and `Float.hash` on the bits. Expected roots and angles are
5
- # rounded doubles (checked against mpmath at 300 bits).
6
+ # the correctly rounded doubles (checked against mpmath at 300 bits).
6
7
  import std/Float
7
8
  import std/Int
8
9
  import std/Str
@@ -106,6 +107,84 @@ test "atan2 with huge ratios, NaNs and infinities"
106
107
  assert math.atan2(1.0f, NaN).isNaN()
107
108
  assert math.atan2(0.0f, NaN).isNaN()
108
109
 
110
+ test "atan to the nearest float across fdlibm's breakpoints"
111
+ # the correctly rounded atan (mpmath, 300 bits); the old series was 165 ulp off at 0.5
112
+ assert math.atan(0.5f) == 0.4636476090008061f
113
+ assert math.atan(0.4375f) == 0.4124104415973873f
114
+ assert math.atan(0.43749999999999994) == 0.41241044159738727
115
+ assert math.atan(0.6875f) == 0.6022873461349642f
116
+ assert math.atan(1.0f) == 0.7853981633974483f
117
+ assert math.atan(1.1875f) == 0.870903457075653f
118
+ assert math.atan(2.4375f) == 1.1814796049617557f
119
+ assert math.atan(3.0f) == 1.2490457723982544f
120
+ assert math.atan(-7.0f) == -1.4288992721907328f
121
+ assert math.atan(0.3f) == 0.2914567944778671f
122
+ assert math.atan(100.0f) == 1.5607966601082315f
123
+ assert math.atan(1.0e-10) == 1.0e-10
124
+ assert math.atan(-Float.Min) == -Float.Min
125
+
126
+ test "asin and acos near the ends of [-1, 1]"
127
+ # acos was Pi/2 - asin(x), 231 ulp off near 1
128
+ assert math.acos(0.9996692316006119) == 0.025721066681572622
129
+ assert math.acos(0.9999999999) == 1.4142136208911564e-05
130
+ assert math.acos(-0.9999999999) == 3.1415785114535844
131
+ # within an ulp (the nearest float is 1.0471975511965979)
132
+ assert {math.acos(0.5f) - 1.0471975511965979f}.abs() <= 2.220446049250313e-16
133
+ assert math.acos(1.0f) == 0.0f
134
+ assert math.acos(-1.0f) == Float.Pi
135
+ assert math.acos(1.5f).isNaN()
136
+ assert math.acos(NaN).isNaN()
137
+ assert math.asin(0.9996692316006119) == 1.545075260113324
138
+ assert math.asin(-0.9999999999) == -1.5707821846586878
139
+ assert math.asin(0.5f) == 0.5235987755982989f
140
+ assert math.asin(0.1f) == 0.1001674211615598f
141
+ assert negZero(math.asin(-0.0f))
142
+ assert math.asin(1.0e-10) == 1.0e-10
143
+ assert math.asin(-1.5f).isNaN()
144
+
145
+ test "atan2 signs its zeros and its Pi as C99 does"
146
+ assert posZero(math.atan2(0.0f, 1.0f))
147
+ assert negZero(math.atan2(-0.0f, 1.0f))
148
+ assert posZero(math.atan2(0.0f, 0.0f))
149
+ assert negZero(math.atan2(-0.0f, 0.0f))
150
+ assert math.atan2(0.0f, -0.0f) == Float.Pi
151
+ assert math.atan2(-0.0f, -0.0f) == -Float.Pi
152
+ assert math.atan2(0.0f, -1.0f) == Float.Pi
153
+ assert math.atan2(-0.0f, -1.0f) == -Float.Pi
154
+ assert math.atan2(-0.0f, -Inf) == -Float.Pi
155
+ assert math.atan2(0.0f, -Inf) == Float.Pi
156
+ assert posZero(math.atan2(0.0f, Inf))
157
+ assert negZero(math.atan2(-0.0f, Inf))
158
+ assert negZero(math.atan2(-1.0f, Inf))
159
+ assert math.atan2(-1.0f, -Inf) == -Float.Pi
160
+ assert math.atan2(1.0f, -Inf) == Float.Pi
161
+ assert math.atan2(1.0f, 0.0f) == Float.HalfPi
162
+ assert math.atan2(1.0f, -0.0f) == Float.HalfPi
163
+ assert math.atan2(-1.0f, 0.0f) == -Float.HalfPi
164
+ assert math.atan2(-1.0f, -0.0f) == -Float.HalfPi
165
+ assert math.atan2(-Inf, 3.0f) == -Float.HalfPi
166
+ assert math.atan2(-Inf, -3.0f) == -Float.HalfPi
167
+
168
+ test "atan2 in every quadrant and at tiny ratios"
169
+ assert math.atan2(1.0f, -1.0f) == 2.356194490192345f
170
+ assert math.atan2(3.0f, -4.0f) == 2.498091544796509f
171
+ assert math.atan2(-3.0f, -4.0f) == -2.498091544796509f
172
+ assert math.atan2(0.2603791574883305, 0.19562622950792052) == 0.9264554678317717
173
+ assert math.atan2(-1.0e-300, -1.0f) == -Float.Pi
174
+ assert math.atan2(1.0e-300, -1.0f) == Float.Pi
175
+ assert math.atan2(1.0e-300, 1.0f) == 1.0e-300
176
+
177
+ test "cbrt rounds to the nearest float"
178
+ # each was one ulp off before the exact-residual step
179
+ assert math.cbrt(-0.34426966240918655) == -0.7008626523891319
180
+ assert math.cbrt(0.5959246308249049) == 0.8415187145490447
181
+ assert math.cbrt(-0.26660774943080734) == -0.6436121829407413
182
+ assert math.cbrt(0.20772079041029634) == 0.5922339804441009
183
+ assert math.cbrt(43.898672966394116) == 3.5276362544751763
184
+ assert math.cbrt(-1.1875000000000064) == -1.0589558960637253
185
+ assert math.cbrt(8.0f) == 2.0f
186
+ assert math.cbrt(Float.fromBits(8)) == Float.fromBits(0x29A0_0000_0000_0000)
187
+
109
188
  test "Int.Min and every Int prints its digits"
110
189
  assert Int.Min.toStr() == "-9223372036854775808"
111
190
  assert Int.Max.toStr() == "9223372036854775807"