plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
86103e5
— Peter John
2026-11-10T14:59:11+05:30
Compiler: a static's call to itself is a self tail call
- benchmarks/static_calls/static_vs_free.plum +42 -0
- compiler/core/src/tail.rs +14 -1
- compiler/core/tests/core/tail_test.rs +16 -0
- std/Decimal.plum +528 -0
- std/Float.plum +9 -44
- std/decimal.plum +0 -436
- std/encoding/Json.plum +4 -4
- tests/std/Decimal.plum +127 -0
- tests/std/decimal.plum +0 -52
benchmarks/static_calls/static_vs_free.plum
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# A static (a `fun` without `self` in a type's body) against the same function at module
|
|
2
|
+
# level: `plum build benchmarks/static_calls/static_vs_free.plum -o /tmp/svf`, then time
|
|
3
|
+
# `/tmp/svf static` and `/tmp/svf free` (process CPU time, 20,000,000 calls of an 18-step
|
|
4
|
+
# loop each).
|
|
5
|
+
#
|
|
6
|
+
# 2026-11-10, debug compiler, wasmtime: before core/src/tail.rs marked a static's call to
|
|
7
|
+
# itself as a self call, `static` took 1.44 s and `free` 0.57 s (the static's loop was a
|
|
8
|
+
# `return_call` per step, the free fn's a branch). With that fixed `static` takes 0.78 s:
|
|
9
|
+
# the rest of the gap is still open (the small static `digit` called from the loop is
|
|
10
|
+
# the suspect: a free fn of that size is inlined).
|
|
11
|
+
import std/Io
|
|
12
|
+
import std/Int
|
|
13
|
+
import std/Float
|
|
14
|
+
import std/Str
|
|
15
|
+
import std/Slice
|
|
16
|
+
|
|
17
|
+
struct Acc(mut n: Int)
|
|
18
|
+
|
|
19
|
+
struct Tool(x: Int) =
|
|
20
|
+
# A static with a self tail call and a small static it calls.
|
|
21
|
+
fun digitsValue(ds: Str, i: Int, j: Int, acc: Int) -> Int =
|
|
22
|
+
if i >= j then acc else digitsValue(ds, i + 1, j, acc * 10 + digit(ds, i))
|
|
23
|
+
|
|
24
|
+
fun digit(ds: Str, i: Int) -> Int = ds.byteAtUnchecked(i) - 48
|
|
25
|
+
|
|
26
|
+
# The same two functions at module level.
|
|
27
|
+
fun digitsValue(ds: Str, i: Int, j: Int, acc: Int) -> Int =
|
|
28
|
+
if i >= j then acc else digitsValue(ds, i + 1, j, acc * 10 + digit(ds, i))
|
|
29
|
+
|
|
30
|
+
fun digit(ds: Str, i: Int) -> Int = ds.byteAtUnchecked(i) - 48
|
|
31
|
+
|
|
32
|
+
fun main(io: Io) =
|
|
33
|
+
mode := io.args().at(0)
|
|
34
|
+
a := Acc(n: 0)
|
|
35
|
+
text := "123456789012345678"
|
|
36
|
+
if mode == "static"
|
|
37
|
+
for r := range 20000000
|
|
38
|
+
a.n = a.n + Tool.digitsValue(text, 0, 18, r)
|
|
39
|
+
else
|
|
40
|
+
for r := range 20000000
|
|
41
|
+
a.n = a.n + digitsValue(text, 0, 18, r)
|
|
42
|
+
io.printLn("{mode} {a.n}")
|
compiler/core/src/tail.rs
CHANGED
|
@@ -32,6 +32,8 @@ pub fn tailCalls(f: &Fn) -> Vec<TailSite> {
|
|
|
32
32
|
|
|
33
33
|
struct Ctx {
|
|
34
34
|
name: String,
|
|
35
|
+
/// The type a method or static belongs to (`None` for a free fn).
|
|
36
|
+
owner: Option<String>,
|
|
35
37
|
isMethod: bool,
|
|
36
38
|
hasSelf: bool,
|
|
37
39
|
locals: HashSet<String>,
|
|
@@ -42,6 +44,7 @@ fn markFn(f: &mut Fn) -> Vec<TailSite> {
|
|
|
42
44
|
let skip = f.is_export || f.is_test;
|
|
43
45
|
let mut cx = Ctx {
|
|
44
46
|
name: f.name.clone(),
|
|
47
|
+
owner: f.type_param.clone(),
|
|
45
48
|
isMethod: f.type_param.is_some(),
|
|
46
49
|
hasSelf: f.has_self,
|
|
47
50
|
locals: f.params.iter().map(|p| p.name.clone()).collect(),
|
|
@@ -153,7 +156,10 @@ fn expr(cx: &mut Ctx, e: &mut Expr, tail: bool) {
|
|
|
153
156
|
TailKind::NotTail
|
|
154
157
|
} else if cx.locals.contains(&c.name) {
|
|
155
158
|
TailKind::Closure
|
|
156
|
-
} else if c.name == cx.name && !cx.isMethod {
|
|
159
|
+
} else if c.name == cx.name && (!cx.isMethod || !cx.hasSelf) {
|
|
160
|
+
// A free fn calling itself, or a static calling itself by its bare name. Should
|
|
161
|
+
// the name resolve to another fn after all (a free fn of the same name), codegen
|
|
162
|
+
// sees a different callee and emits a plain tail call.
|
|
157
163
|
TailKind::SelfCall
|
|
158
164
|
} else {
|
|
159
165
|
TailKind::Other
|
|
@@ -165,10 +171,17 @@ fn expr(cx: &mut Ctx, e: &mut Expr, tail: bool) {
|
|
|
165
171
|
if let AttrKind::Method(c) = &mut a.attr {
|
|
166
172
|
args(cx, &mut c.args);
|
|
167
173
|
let onSelf = matches!(a.object.kind, ExprKind::Self_);
|
|
174
|
+
// `Type.name(..)` inside the static `name` of `Type`.
|
|
175
|
+
let onOwner = match (&a.object.kind, &cx.owner) {
|
|
176
|
+
(ExprKind::TypeName(t) | ExprKind::Var(t), Some(o)) => t == o,
|
|
177
|
+
_ => false,
|
|
178
|
+
};
|
|
168
179
|
c.tail = if !tail {
|
|
169
180
|
TailKind::NotTail
|
|
170
181
|
} else if onSelf && cx.hasSelf && c.name == cx.name && cx.isMethod {
|
|
171
182
|
TailKind::SelfCall
|
|
183
|
+
} else if onOwner && !cx.hasSelf && c.name == cx.name {
|
|
184
|
+
TailKind::SelfCall
|
|
172
185
|
} else {
|
|
173
186
|
TailKind::Other
|
|
174
187
|
};
|
compiler/core/tests/core/tail_test.rs
CHANGED
|
@@ -82,6 +82,22 @@ fn method_self_tail() {
|
|
|
82
82
|
assert_eq!(sites(src, "count"), one("count", TailKind::SelfCall));
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
+
/// A static calling itself, by its bare name or as `Type.name(..)`, is a self call like a free
|
|
86
|
+
/// fn's, so codegen turns it into a loop. A static calling a method of the same name is not.
|
|
87
|
+
#[test]
|
|
88
|
+
fn static_self_tail() {
|
|
89
|
+
let src = "struct Tool(x: Int) =\n fun count(k: Int, acc: Int) -> Int =\n if k == 0 then acc else count(k - 1, acc + 1)\n";
|
|
90
|
+
assert_eq!(sites(src, "count"), one("count", TailKind::SelfCall));
|
|
91
|
+
let src = "struct Tool(x: Int) =\n fun count(k: Int, acc: Int) -> Int =\n if k == 0 then acc else Tool.count(k - 1, acc + 1)\n";
|
|
92
|
+
assert_eq!(sites(src, "count"), one("count", TailKind::SelfCall));
|
|
93
|
+
let src = "primitive Tool =\n fun count(k: Int, acc: Int) -> Int =\n if k == 0 then acc else Tool.count(k - 1, acc + 1)\n";
|
|
94
|
+
assert_eq!(sites(src, "count"), one("count", TailKind::SelfCall));
|
|
95
|
+
let src = "struct Tool(x: Int) =\n fun count(k: Int, acc: Int) -> Int =\n if k == 0 then acc else Other.count(k - 1, acc + 1)\n";
|
|
96
|
+
assert_eq!(sites(src, "count"), one("count", TailKind::Other));
|
|
97
|
+
let src = "struct Tool(x: Int) =\n fun count(self, k: Int) -> Int =\n if k == 0 then self.x else Tool.count(k - 1)\n";
|
|
98
|
+
assert_eq!(sites(src, "count"), one("count", TailKind::Other));
|
|
99
|
+
}
|
|
100
|
+
|
|
85
101
|
#[test]
|
|
86
102
|
fn closure_value_call_tail() {
|
|
87
103
|
let src = "fun f(g: fn(Int) -> Int, n: Int) -> Int = g(n)\n";
|
std/Decimal.plum
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
module std
|
|
2
|
+
|
|
3
|
+
import std/Int
|
|
4
|
+
import std/Float
|
|
5
|
+
import std/Str
|
|
6
|
+
import std/Buffer
|
|
7
|
+
import std/Byte
|
|
8
|
+
import std/Slice
|
|
9
|
+
import std/Option
|
|
10
|
+
import std/Pair
|
|
11
|
+
import std/math/math
|
|
12
|
+
|
|
13
|
+
# What `Decimal.parse` reads off the text as it goes: the significant digits (no point),
|
|
14
|
+
# the power of ten they are scaled by, the sign, and whether the text is a number at all.
|
|
15
|
+
struct DecimalScan(mut digits: Buffer, mut exp: Int, mut neg: Bool, mut ok: Bool, mut seen: Int, mut pos: Int)
|
|
16
|
+
|
|
17
|
+
# A Decimal is an exact decimal number: `digits * 10^exp`, negated when `neg`. `digits` is
|
|
18
|
+
# a string of decimal digits with no leading zero (`"0"` for zero, which keeps its sign),
|
|
19
|
+
# so `Decimal(digits: "15", exp: -1, neg: false)` is 1.5.
|
|
20
|
+
#
|
|
21
|
+
# - `Decimal.parse(text)` reads `[+-]digits[.digits][(e|E)[+-]digits]` (digits on at least
|
|
22
|
+
# one side of the point) exactly, with no rounding: `0.1` is 1 * 10^-1, not a Float near
|
|
23
|
+
# it, and `1.50` keeps its zero (150 * 10^-2).
|
|
24
|
+
# - `d.toFloat()` is the Float nearest `d`, ties to even, as IEEE 754 and every correct
|
|
25
|
+
# `strtod` give: `0.3` is the Float literal `0.3`, `1e400` is Infinity, `1e-400` is 0.0.
|
|
26
|
+
# Up to 15 digits and a power of ten up to 22 it is one Float multiply or divide (both
|
|
27
|
+
# operands exact, so rounded once); otherwise a Float estimate is stepped to the nearest
|
|
28
|
+
# Float by comparing the exact value with the halfway points between Floats in big
|
|
29
|
+
# integer arithmetic.
|
|
30
|
+
# - `Decimal.ofFloat(x)` is the shortest digits that convert back to `x` (Burger and
|
|
31
|
+
# Dybvig's free-format algorithm, exact in big integers), and `Decimal.exact(x)` is the
|
|
32
|
+
# value `x` holds exactly (every finite Float is a whole number times a power of two, so
|
|
33
|
+
# it has one: `Decimal.exact(0.1)` has 55 digits).
|
|
34
|
+
# - `d.toStr()` writes the digits the way JavaScript's `String(x)` does: `0.1`, `123`,
|
|
35
|
+
# `1e+21`, `1.5e-7`.
|
|
36
|
+
#
|
|
37
|
+
# The helpers below the public functions (`big..`, the scanner, `nearest`, `generate`) are
|
|
38
|
+
# statics of `Decimal` only so that they are not free functions of a module: the language
|
|
39
|
+
# has no private members, so `Decimal.bigAdd` can still be written, but nothing outside
|
|
40
|
+
# this file should. A big integer there is a `Slice[Int]` of 28-bit limbs, least
|
|
41
|
+
# significant first, with no zero limb on top (zero is the empty slice). Products of two
|
|
42
|
+
# limbs fit an Int with room for a carry.
|
|
43
|
+
struct Decimal(digits: Str, exp: Int, neg: Bool) =
|
|
44
|
+
LimbBits = 28
|
|
45
|
+
LimbMask = 0xFFF_FFFF
|
|
46
|
+
|
|
47
|
+
# The decimal `text` exactly, or None if it isn't a number (see the top of the file).
|
|
48
|
+
fun parse(text: Str) -> Option[Decimal] =
|
|
49
|
+
sc := DecimalScan(digits: Buffer(), exp: 0, neg: false, ok: true, seen: 0, pos: 0)
|
|
50
|
+
if scan(text, sc)
|
|
51
|
+
if sc.digits.length() == 0
|
|
52
|
+
Some(Decimal(digits: "0", exp: 0, neg: sc.neg))
|
|
53
|
+
else
|
|
54
|
+
Some(Decimal(digits: sc.digits.toStr(), exp: sc.exp, neg: sc.neg))
|
|
55
|
+
else
|
|
56
|
+
None
|
|
57
|
+
|
|
58
|
+
# The Float nearest this decimal, ties to even; an infinity past Float's range, a zero
|
|
59
|
+
# below it. `-0` is `-0.0`.
|
|
60
|
+
fun toFloat(self) -> Float =
|
|
61
|
+
v := digitsToFloat(self.digits, self.exp)
|
|
62
|
+
if self.neg then -v else v
|
|
63
|
+
|
|
64
|
+
# The shortest decimal that converts back to `x` with `toFloat`: `Decimal.ofFloat(0.1)`
|
|
65
|
+
# is 1 * 10^-1 and `Decimal.ofFloat(1e21)` is 1 * 10^21. `x` must be finite: a NaN or an
|
|
66
|
+
# infinity has no decimal value, and stops the program.
|
|
67
|
+
fun ofFloat(x: Float) -> Decimal =
|
|
68
|
+
if x != x || x > Float.Max || x < 0.0 - Float.Max
|
|
69
|
+
crash "Decimal.ofFloat: {x} is not a finite number"
|
|
70
|
+
else if x == 0.0
|
|
71
|
+
Decimal(digits: "0", exp: 0, neg: 1.0 / x < 0.0)
|
|
72
|
+
else
|
|
73
|
+
a := if x < 0.0 then 0.0 - x else x
|
|
74
|
+
if a < 9007199254740992.0 && a.trunc() == a
|
|
75
|
+
trimmed(Int(a).toStr(), 0, x < 0.0)
|
|
76
|
+
else
|
|
77
|
+
shortest(a, x < 0.0)
|
|
78
|
+
|
|
79
|
+
# The value the finite Float `x` holds, exactly: `Decimal.exact(0.5)` is 5 * 10^-1,
|
|
80
|
+
# `Decimal.exact(1e23)` is 99999999999999991611392, and `Decimal.exact(0.1)` is
|
|
81
|
+
# 0.1000000000000000055511151231257827021181583404541015625. A NaN or an infinity stops
|
|
82
|
+
# the program.
|
|
83
|
+
fun exact(x: Float) -> Decimal =
|
|
84
|
+
if x != x || x > Float.Max || x < 0.0 - Float.Max
|
|
85
|
+
crash "Decimal.exact: {x} is not a finite number"
|
|
86
|
+
else if x == 0.0
|
|
87
|
+
Decimal(digits: "0", exp: 0, neg: 1.0 / x < 0.0)
|
|
88
|
+
else
|
|
89
|
+
bits := x.toBits() & 0x7FFF_FFFF_FFFF_FFFF
|
|
90
|
+
expo := bits >> 52
|
|
91
|
+
frac := bits & 0xF_FFFF_FFFF_FFFF
|
|
92
|
+
f0 := if expo == 0 then frac else frac | 0x10_0000_0000_0000
|
|
93
|
+
e0 := if expo == 0 then -1074 else expo - 1075
|
|
94
|
+
# x = f0 * 2^e0. Below one, halve f0 while it is even: then f * 2^e = f * 5^-e * 10^e.
|
|
95
|
+
tz := f0.trailingZeros()
|
|
96
|
+
drop := if e0 >= 0 then 0 else if tz < 0 - e0 then tz else 0 - e0
|
|
97
|
+
f := f0 >> drop
|
|
98
|
+
e := e0 + drop
|
|
99
|
+
if e >= 0
|
|
100
|
+
trimmed(bigToDigits(bigShl(bigOf(f), e)), 0, x < 0.0)
|
|
101
|
+
else
|
|
102
|
+
m := bigOf(f)
|
|
103
|
+
bigMulPow5(m, 0 - e)
|
|
104
|
+
Decimal(digits: bigToDigits(m), exp: e, neg: x < 0.0)
|
|
105
|
+
|
|
106
|
+
# The decimal as JavaScript's `String(x)` writes a number (and JSON with it): its digits
|
|
107
|
+
# in plain notation from 1e-6 up to 1e21 (`0.000001`, `123.5`, `100000000000000000000`)
|
|
108
|
+
# and in exponent notation outside it (`1e+21`, `1.5e-7`), `-0` for minus zero. So
|
|
109
|
+
# `Decimal.ofFloat(x).toStr()` is the shortest text that reads back as `x`.
|
|
110
|
+
fun toStr(self) -> Str =
|
|
111
|
+
ds := self.digits
|
|
112
|
+
n := ds.length()
|
|
113
|
+
k := n + self.exp
|
|
114
|
+
body := if self.exp == 0 && n <= 21
|
|
115
|
+
ds
|
|
116
|
+
else if k >= n && k <= 21
|
|
117
|
+
ds + "0".repeat(k - n)
|
|
118
|
+
else if k > 0 && k <= 21
|
|
119
|
+
ds.sub(0, k) + "." + ds.sub(k, n)
|
|
120
|
+
else if k > -6 && k <= 0
|
|
121
|
+
"0." + "0".repeat(0 - k) + ds
|
|
122
|
+
else
|
|
123
|
+
mant := if n == 1 then ds else ds.sub(0, 1) + "." + ds.sub(1, n)
|
|
124
|
+
x10 := k - 1
|
|
125
|
+
mant + "e" + {if x10 < 0 then "-" else "+"} + {if x10 < 0 then 0 - x10 else x10}.toStr()
|
|
126
|
+
if self.neg then "-" + body else body
|
|
127
|
+
|
|
128
|
+
# True for 0 and -0.
|
|
129
|
+
fun isZero(self) -> Bool = self.digits == "0"
|
|
130
|
+
|
|
131
|
+
# `digits * 10^exp` with the trailing zeros of `digits` moved into the exponent.
|
|
132
|
+
fun trimmed(digits: Str, exp: Int, neg: Bool) -> Decimal =
|
|
133
|
+
b := lastNonZero(digits, digits.length() - 1)
|
|
134
|
+
if b == digits.length() - 1
|
|
135
|
+
Decimal(digits: digits, exp: exp, neg: neg)
|
|
136
|
+
else
|
|
137
|
+
Decimal(digits: digits.sub(0, b + 1), exp: exp + digits.length() - 1 - b, neg: neg)
|
|
138
|
+
|
|
139
|
+
# ---- decimal text ----
|
|
140
|
+
|
|
141
|
+
# Reads all of `text` into `sc`; false if it isn't a number.
|
|
142
|
+
fun scan(text: Str, sc: DecimalScan) -> Bool =
|
|
143
|
+
n := text.length()
|
|
144
|
+
if n > 0 && {text.byteAt(0) == 45 || text.byteAt(0) == 43}
|
|
145
|
+
sc.neg = text.byteAt(0) == 45
|
|
146
|
+
sc.pos = 1
|
|
147
|
+
scanDigits(text, sc, false)
|
|
148
|
+
if sc.pos < n && text.byteAt(sc.pos) == 46
|
|
149
|
+
sc.pos = sc.pos + 1
|
|
150
|
+
scanDigits(text, sc, true)
|
|
151
|
+
if sc.seen == 0
|
|
152
|
+
sc.ok = false
|
|
153
|
+
if sc.ok && sc.pos < n && {text.byteAt(sc.pos) == 101 || text.byteAt(sc.pos) == 69}
|
|
154
|
+
sc.pos = sc.pos + 1
|
|
155
|
+
eneg := sc.pos < n && text.byteAt(sc.pos) == 45
|
|
156
|
+
if sc.pos < n && {text.byteAt(sc.pos) == 45 || text.byteAt(sc.pos) == 43}
|
|
157
|
+
sc.pos = sc.pos + 1
|
|
158
|
+
start := sc.pos
|
|
159
|
+
e := expDigits(text, sc, 0)
|
|
160
|
+
if sc.pos == start
|
|
161
|
+
sc.ok = false
|
|
162
|
+
sc.exp = sc.exp + {if eneg then 0 - e else e}
|
|
163
|
+
sc.ok && sc.pos == n
|
|
164
|
+
|
|
165
|
+
# Reads digits from `sc.pos` on into `sc.digits` (leading zeros of the number skipped); a
|
|
166
|
+
# digit after the point lowers the exponent by one.
|
|
167
|
+
fun scanDigits(text: Str, sc: DecimalScan, frac: Bool) -> Unit =
|
|
168
|
+
if sc.pos < text.length()
|
|
169
|
+
b := text.byteAtUnchecked(sc.pos)
|
|
170
|
+
if b >= 48 && b <= 57
|
|
171
|
+
if b != 48 || sc.digits.length() > 0
|
|
172
|
+
sc.digits.writeByte(Byte(b))
|
|
173
|
+
if frac
|
|
174
|
+
sc.exp = sc.exp - 1
|
|
175
|
+
sc.seen = sc.seen + 1
|
|
176
|
+
sc.pos = sc.pos + 1
|
|
177
|
+
scanDigits(text, sc, frac)
|
|
178
|
+
|
|
179
|
+
# The exponent's digits from `sc.pos` on, held at a million (far past any Float).
|
|
180
|
+
fun expDigits(text: Str, sc: DecimalScan, acc: Int) -> Int =
|
|
181
|
+
if sc.pos < text.length() && text.byteAtUnchecked(sc.pos) >= 48 && text.byteAtUnchecked(sc.pos) <= 57
|
|
182
|
+
d := text.byteAtUnchecked(sc.pos) - 48
|
|
183
|
+
sc.pos = sc.pos + 1
|
|
184
|
+
expDigits(text, sc, if acc > 1000000 then acc else acc * 10 + d)
|
|
185
|
+
else
|
|
186
|
+
acc
|
|
187
|
+
|
|
188
|
+
# The Float nearest `digits * 10^exp`, for a string of decimal digits (zeros allowed at
|
|
189
|
+
# either end, or none at all: zero).
|
|
190
|
+
fun digitsToFloat(digits: Str, exp: Int) -> Float =
|
|
191
|
+
a := firstNonZero(digits, 0)
|
|
192
|
+
if a >= digits.length()
|
|
193
|
+
0.0
|
|
194
|
+
else
|
|
195
|
+
b := lastNonZero(digits, digits.length() - 1)
|
|
196
|
+
ds := digits.sub(a, b + 1)
|
|
197
|
+
e := exp + {digits.length() - 1 - b}
|
|
198
|
+
n := ds.length()
|
|
199
|
+
if n + e > 310
|
|
200
|
+
1.0 / 0.0
|
|
201
|
+
else if n + e < -324
|
|
202
|
+
0.0
|
|
203
|
+
else if n <= 15 && e >= -22 && e <= 22
|
|
204
|
+
m := Float(digitsValue(ds, 0, n, 0))
|
|
205
|
+
if e >= 0 then m * pow10Exact(e) else m / pow10Exact(0 - e)
|
|
206
|
+
else
|
|
207
|
+
k := if n < 18 then n else 18
|
|
208
|
+
guess := scaleApprox(Float(digitsValue(ds, 0, k, 0)), e + n - k)
|
|
209
|
+
big := bigOfDigits(ds, 0, n, Slice[Int]())
|
|
210
|
+
left := if e >= 0 then bigMulPow10(big, e) else big
|
|
211
|
+
nearest(left, if e >= 0 then 0 else e, guess)
|
|
212
|
+
|
|
213
|
+
fun firstNonZero(s: Str, i: Int) -> Int =
|
|
214
|
+
if i < s.length() && s.byteAtUnchecked(i) == 48 then firstNonZero(s, i + 1) else i
|
|
215
|
+
|
|
216
|
+
fun lastNonZero(s: Str, i: Int) -> Int =
|
|
217
|
+
if i > 0 && s.byteAtUnchecked(i) == 48 then lastNonZero(s, i - 1) else i
|
|
218
|
+
|
|
219
|
+
# The exact value is `left * 10^e` (e <= 0; with e = 0 `left` already holds the whole
|
|
220
|
+
# value). Steps `z` one Float at a time until it is the one nearest that value.
|
|
221
|
+
fun nearest(left: Slice[Int], e: Int, z: Float) -> Float =
|
|
222
|
+
if z > Float.Max
|
|
223
|
+
z
|
|
224
|
+
else
|
|
225
|
+
bits := z.toBits()
|
|
226
|
+
expo := {bits >> 52} & 0x7FF
|
|
227
|
+
frac := bits & 0xF_FFFF_FFFF_FFFF
|
|
228
|
+
mz := if expo == 0 then frac else frac | 0x10_0000_0000_0000
|
|
229
|
+
ez := if expo == 0 then -1074 else expo - 1075
|
|
230
|
+
up := cmpExact(left, e, 2 * mz + 1, ez - 1)
|
|
231
|
+
if up > 0
|
|
232
|
+
nearest(left, e, Float.fromBits(bits + 1))
|
|
233
|
+
else if up == 0
|
|
234
|
+
if mz % 2 == 0 then z else Float.fromBits(bits + 1)
|
|
235
|
+
else if mz == 0
|
|
236
|
+
z
|
|
237
|
+
else
|
|
238
|
+
down := if frac == 0 && expo > 1 then cmpExact(left, e, 4 * mz - 1, ez - 2) else cmpExact(left, e, 2 * mz - 1, ez - 1)
|
|
239
|
+
if down < 0
|
|
240
|
+
nearest(left, e, Float.fromBits(bits - 1))
|
|
241
|
+
else if down == 0
|
|
242
|
+
if mz % 2 == 0 then z else Float.fromBits(bits - 1)
|
|
243
|
+
else
|
|
244
|
+
z
|
|
245
|
+
|
|
246
|
+
# The sign of `left * 10^e - m * 2^s`, exactly (e <= 0, m > 0).
|
|
247
|
+
fun cmpExact(left: Slice[Int], e: Int, m: Int, s: Int) -> Int =
|
|
248
|
+
right := bigOf(m)
|
|
249
|
+
bigMulPow5(right, 0 - e)
|
|
250
|
+
# left * 2^e against right * 2^s.
|
|
251
|
+
d := e - s
|
|
252
|
+
if d >= 0 then bigCmp(bigShl(left, d), right) else bigCmp(left, bigShl(right, 0 - d))
|
|
253
|
+
|
|
254
|
+
# ---- Float to the shortest decimal ----
|
|
255
|
+
|
|
256
|
+
# The shortest digits of `x` that convert back to it. `x` must be finite and above 0.
|
|
257
|
+
fun shortest(x: Float, neg: Bool) -> Decimal =
|
|
258
|
+
bits := x.toBits()
|
|
259
|
+
expo := {bits >> 52} & 0x7FF
|
|
260
|
+
frac := bits & 0xF_FFFF_FFFF_FFFF
|
|
261
|
+
f := if expo == 0 then frac else frac | 0x10_0000_0000_0000
|
|
262
|
+
e := if expo == 0 then -1074 else expo - 1075
|
|
263
|
+
even := f % 2 == 0
|
|
264
|
+
# Twice the value and the gaps to the neighbouring Floats, as r / s, mp / s and mm / s.
|
|
265
|
+
lowGap := frac == 0 && expo > 1
|
|
266
|
+
r0 := if e >= 0
|
|
267
|
+
if lowGap then bigShl(bigOf(f), e + 2) else bigShl(bigOf(f), e + 1)
|
|
268
|
+
else
|
|
269
|
+
if lowGap then bigOf(4 * f) else bigOf(2 * f)
|
|
270
|
+
s0 := if e >= 0
|
|
271
|
+
if lowGap then bigOf(4) else bigOf(2)
|
|
272
|
+
else
|
|
273
|
+
if lowGap then bigShl(bigOf(1), 2 - e) else bigShl(bigOf(1), 1 - e)
|
|
274
|
+
mp0 := if e >= 0
|
|
275
|
+
if lowGap then bigShl(bigOf(1), e + 1) else bigShl(bigOf(1), e)
|
|
276
|
+
else
|
|
277
|
+
if lowGap then bigOf(2) else bigOf(1)
|
|
278
|
+
mm0 := if e >= 0 then bigShl(bigOf(1), e) else bigOf(1)
|
|
279
|
+
bitLen := 64 - f.leadingZeros()
|
|
280
|
+
k := Int({Float(e + bitLen - 1) * 0.30102999566398114 - 0.0000000001}.ceil())
|
|
281
|
+
r := if k >= 0 then r0 else bigMulPow10(r0, 0 - k)
|
|
282
|
+
s := if k >= 0 then bigMulPow10(s0, k) else s0
|
|
283
|
+
mp := if k >= 0 then mp0 else bigMulPow10(mp0, 0 - k)
|
|
284
|
+
mm := if k >= 0 then mm0 else bigMulPow10(mm0, 0 - k)
|
|
285
|
+
high := bigCmp(bigAdd(r, mp), s)
|
|
286
|
+
out := Buffer()
|
|
287
|
+
if high > 0 || even && high == 0
|
|
288
|
+
generate(r, s, mp, mm, even, out)
|
|
289
|
+
ds := out.toStr()
|
|
290
|
+
Decimal(digits: ds, exp: k + 1 - ds.length(), neg: neg)
|
|
291
|
+
else
|
|
292
|
+
generate(bigMulPow10(r, 1), s, bigMulPow10(mp, 1), bigMulPow10(mm, 1), even, out)
|
|
293
|
+
ds := out.toStr()
|
|
294
|
+
Decimal(digits: ds, exp: k - ds.length(), neg: neg)
|
|
295
|
+
|
|
296
|
+
# Writes the digits of r / s into `out` until the digits so far are within the gaps
|
|
297
|
+
# (inclusive when `even`: a tie parses to the even Float, which is `x`).
|
|
298
|
+
fun generate(r: Slice[Int], s: Slice[Int], mp: Slice[Int], mm: Slice[Int], even: Bool, out: Buffer) -> Unit =
|
|
299
|
+
q := quotientDigit(r, s, 0)
|
|
300
|
+
rest := q.second
|
|
301
|
+
d := q.first
|
|
302
|
+
low := bigCmp(rest, mm)
|
|
303
|
+
tc1 := low < 0 || even && low == 0
|
|
304
|
+
high := bigCmp(bigAdd(rest, mp), s)
|
|
305
|
+
tc2 := high > 0 || even && high == 0
|
|
306
|
+
if !tc1 && !tc2
|
|
307
|
+
out.writeByte(Byte(48 + d))
|
|
308
|
+
generate(bigMulPow10(rest, 1), s, bigMulPow10(mp, 1), bigMulPow10(mm, 1), even, out)
|
|
309
|
+
else if tc1 && !tc2
|
|
310
|
+
out.writeByte(Byte(48 + d))
|
|
311
|
+
else if !tc1 && tc2
|
|
312
|
+
out.writeByte(Byte(49 + d))
|
|
313
|
+
else
|
|
314
|
+
half := bigCmp(bigShl(rest, 1), s)
|
|
315
|
+
out.writeByte(Byte(if half < 0 then 48 + d else 49 + d))
|
|
316
|
+
|
|
317
|
+
# r / s as a digit 0..9 and the remainder, by subtracting (r < 10 s).
|
|
318
|
+
fun quotientDigit(r: Slice[Int], s: Slice[Int], d: Int) -> Pair[Int, Slice[Int]] =
|
|
319
|
+
if bigCmp(r, s) < 0 then Pair(first: d, second: r) else quotientDigit(bigSub(r, s), s, d + 1)
|
|
320
|
+
|
|
321
|
+
# ---- big integer to decimal digits ----
|
|
322
|
+
|
|
323
|
+
# The decimal digits of `a` (above zero), most significant first. `a` is used up.
|
|
324
|
+
fun bigToDigits(a: Slice[Int]) -> Str =
|
|
325
|
+
chunks := Slice[Int]()
|
|
326
|
+
bigChunks(a, chunks)
|
|
327
|
+
out := Buffer()
|
|
328
|
+
out.write(chunks.at(chunks.length() - 1).toStr())
|
|
329
|
+
writeChunks(chunks, chunks.length() - 2, out)
|
|
330
|
+
out.toStr()
|
|
331
|
+
|
|
332
|
+
# Divides `a` by 10^8 until nothing is left, pushing each remainder (eight digits, the
|
|
333
|
+
# least significant first).
|
|
334
|
+
fun bigChunks(a: Slice[Int], chunks: Slice[Int]) -> Unit =
|
|
335
|
+
if a.length() > 0
|
|
336
|
+
chunks.push(divSmallFrom(a, 100000000, a.length() - 1, 0))
|
|
337
|
+
trimTop(a)
|
|
338
|
+
bigChunks(a, chunks)
|
|
339
|
+
|
|
340
|
+
# `a = a / d` in place from limb `i` down, for 0 < d < 2^28; returns the remainder.
|
|
341
|
+
fun divSmallFrom(a: Slice[Int], d: Int, i: Int, rem: Int) -> Int =
|
|
342
|
+
if i < 0
|
|
343
|
+
rem
|
|
344
|
+
else
|
|
345
|
+
cur := {rem << Decimal.LimbBits} | a.atUnchecked(i)
|
|
346
|
+
a.putAt(i, cur / d)
|
|
347
|
+
divSmallFrom(a, d, i - 1, cur % d)
|
|
348
|
+
|
|
349
|
+
# Chunks `i` down to 0, eight digits each.
|
|
350
|
+
fun writeChunks(chunks: Slice[Int], i: Int, out: Buffer) -> Unit =
|
|
351
|
+
if i >= 0
|
|
352
|
+
out.write(Int.fixedFracDigits(chunks.at(i), 10000000))
|
|
353
|
+
writeChunks(chunks, i - 1, out)
|
|
354
|
+
|
|
355
|
+
# ---- big integers ----
|
|
356
|
+
|
|
357
|
+
fun bigOf(n: Int) -> Slice[Int] =
|
|
358
|
+
out := Slice[Int]()
|
|
359
|
+
pushLimbs(out, n)
|
|
360
|
+
out
|
|
361
|
+
|
|
362
|
+
# Appends the limbs of `n` (n >= 0) on top of `out`.
|
|
363
|
+
fun pushLimbs(out: Slice[Int], n: Int) -> Unit =
|
|
364
|
+
if n > 0
|
|
365
|
+
out.push(n & Decimal.LimbMask)
|
|
366
|
+
pushLimbs(out, n >> Decimal.LimbBits)
|
|
367
|
+
|
|
368
|
+
fun bigCopy(a: Slice[Int]) -> Slice[Int] = a.sublist(0, a.length())
|
|
369
|
+
|
|
370
|
+
# `a = a * f + add` in place, for 0 < f < 2^28 and 0 <= add < 2^28.
|
|
371
|
+
fun bigMulAdd(a: Slice[Int], f: Int, add: Int) -> Unit =
|
|
372
|
+
pushLimbs(a, mulAddFrom(a, f, 0, add))
|
|
373
|
+
|
|
374
|
+
fun mulAddFrom(a: Slice[Int], f: Int, i: Int, carry: Int) -> Int =
|
|
375
|
+
if i >= a.length()
|
|
376
|
+
carry
|
|
377
|
+
else
|
|
378
|
+
p := a.atUnchecked(i) * f + carry
|
|
379
|
+
a.putAt(i, p & Decimal.LimbMask)
|
|
380
|
+
mulAddFrom(a, f, i + 1, p >> Decimal.LimbBits)
|
|
381
|
+
|
|
382
|
+
# `a * 5^k`, in place.
|
|
383
|
+
fun bigMulPow5(a: Slice[Int], k: Int) -> Unit =
|
|
384
|
+
if k >= 12
|
|
385
|
+
bigMulAdd(a, 244140625, 0)
|
|
386
|
+
bigMulPow5(a, k - 12)
|
|
387
|
+
else if k > 0
|
|
388
|
+
bigMulAdd(a, pow5(k), 0)
|
|
389
|
+
|
|
390
|
+
fun pow5(k: Int) -> Int = if k <= 0 then 1 else 5 * pow5(k - 1)
|
|
391
|
+
|
|
392
|
+
# A new big integer: `a * 2^k` (k >= 0).
|
|
393
|
+
fun bigShl(a: Slice[Int], k: Int) -> Slice[Int] =
|
|
394
|
+
if a.isEmpty() || k == 0
|
|
395
|
+
bigCopy(a)
|
|
396
|
+
else
|
|
397
|
+
b := bigCopy(a)
|
|
398
|
+
bigMulAdd(b, 1 << {k % Decimal.LimbBits}, 0)
|
|
399
|
+
out := Slice[Int]()
|
|
400
|
+
for _ := range k / Decimal.LimbBits
|
|
401
|
+
out.push(0)
|
|
402
|
+
out.add(b)
|
|
403
|
+
out
|
|
404
|
+
|
|
405
|
+
# A new big integer: `a * 10^k` (k >= 0).
|
|
406
|
+
fun bigMulPow10(a: Slice[Int], k: Int) -> Slice[Int] =
|
|
407
|
+
b := bigCopy(a)
|
|
408
|
+
bigMulPow5(b, k)
|
|
409
|
+
bigShl(b, k)
|
|
410
|
+
|
|
411
|
+
# -1, 0 or 1 as `a` is below, equal to or above `b`.
|
|
412
|
+
fun bigCmp(a: Slice[Int], b: Slice[Int]) -> Int =
|
|
413
|
+
if a.length() != b.length()
|
|
414
|
+
if a.length() < b.length() then -1 else 1
|
|
415
|
+
else
|
|
416
|
+
cmpFrom(a, b, a.length() - 1)
|
|
417
|
+
|
|
418
|
+
fun cmpFrom(a: Slice[Int], b: Slice[Int], i: Int) -> Int =
|
|
419
|
+
if i < 0
|
|
420
|
+
0
|
|
421
|
+
else
|
|
422
|
+
x := a.atUnchecked(i)
|
|
423
|
+
y := b.atUnchecked(i)
|
|
424
|
+
if x != y
|
|
425
|
+
if x < y then -1 else 1
|
|
426
|
+
else
|
|
427
|
+
cmpFrom(a, b, i - 1)
|
|
428
|
+
|
|
429
|
+
# A new big integer: `a + b`.
|
|
430
|
+
fun bigAdd(a: Slice[Int], b: Slice[Int]) -> Slice[Int] =
|
|
431
|
+
out := Slice[Int]()
|
|
432
|
+
n := if a.length() > b.length() then a.length() else b.length()
|
|
433
|
+
addFrom(a, b, out, 0, n, 0)
|
|
434
|
+
out
|
|
435
|
+
|
|
436
|
+
fun addFrom(a: Slice[Int], b: Slice[Int], out: Slice[Int], i: Int, n: Int, carry: Int) -> Unit =
|
|
437
|
+
if i < n
|
|
438
|
+
s := limbAt(a, i) + limbAt(b, i) + carry
|
|
439
|
+
out.push(s & Decimal.LimbMask)
|
|
440
|
+
addFrom(a, b, out, i + 1, n, s >> Decimal.LimbBits)
|
|
441
|
+
else if carry > 0
|
|
442
|
+
out.push(carry)
|
|
443
|
+
|
|
444
|
+
# A new big integer: `a - b`, for a >= b.
|
|
445
|
+
fun bigSub(a: Slice[Int], b: Slice[Int]) -> Slice[Int] =
|
|
446
|
+
out := Slice[Int]()
|
|
447
|
+
subFrom(a, b, out, 0, 0)
|
|
448
|
+
trimTop(out)
|
|
449
|
+
out
|
|
450
|
+
|
|
451
|
+
fun subFrom(a: Slice[Int], b: Slice[Int], out: Slice[Int], i: Int, borrow: Int) -> Unit =
|
|
452
|
+
if i < a.length()
|
|
453
|
+
d := a.atUnchecked(i) - limbAt(b, i) - borrow
|
|
454
|
+
out.push(if d < 0 then d + {1 << Decimal.LimbBits} else d)
|
|
455
|
+
subFrom(a, b, out, i + 1, if d < 0 then 1 else 0)
|
|
456
|
+
|
|
457
|
+
fun limbAt(a: Slice[Int], i: Int) -> Int = if i < a.length() then a.atUnchecked(i) else 0
|
|
458
|
+
|
|
459
|
+
# Drops zero limbs from the top.
|
|
460
|
+
fun trimTop(a: Slice[Int]) -> Unit =
|
|
461
|
+
if a.length() > 0 && a.atUnchecked(a.length() - 1) == 0
|
|
462
|
+
_ := a.pop()
|
|
463
|
+
trimTop(a)
|
|
464
|
+
|
|
465
|
+
# The big integer of the decimal digits `ds[i..j)`, eight digits per step.
|
|
466
|
+
fun bigOfDigits(ds: Str, i: Int, j: Int, acc: Slice[Int]) -> Slice[Int] =
|
|
467
|
+
if i >= j
|
|
468
|
+
acc
|
|
469
|
+
else
|
|
470
|
+
k := if j - i < 8 then j - i else 8
|
|
471
|
+
v := digitsValue(ds, i, i + k, 0)
|
|
472
|
+
bigMulAdd(acc, pow10Int(k), 0)
|
|
473
|
+
bigAddSmall(acc, v)
|
|
474
|
+
bigOfDigits(ds, i + k, j, acc)
|
|
475
|
+
|
|
476
|
+
# `a + v` in place, for 0 <= v < 2^28.
|
|
477
|
+
fun bigAddSmall(a: Slice[Int], v: Int) -> Unit =
|
|
478
|
+
pushLimbs(a, addSmallFrom(a, 0, v))
|
|
479
|
+
|
|
480
|
+
fun addSmallFrom(a: Slice[Int], i: Int, carry: Int) -> Int =
|
|
481
|
+
if carry == 0 || i >= a.length()
|
|
482
|
+
carry
|
|
483
|
+
else
|
|
484
|
+
s := a.atUnchecked(i) + carry
|
|
485
|
+
a.putAt(i, s & Decimal.LimbMask)
|
|
486
|
+
addSmallFrom(a, i + 1, s >> Decimal.LimbBits)
|
|
487
|
+
|
|
488
|
+
fun digitsValue(ds: Str, i: Int, j: Int, acc: Int) -> Int =
|
|
489
|
+
if i >= j then acc else digitsValue(ds, i + 1, j, acc * 10 + ds.byteAtUnchecked(i) - 48)
|
|
490
|
+
|
|
491
|
+
fun pow10Int(k: Int) -> Int = if k <= 0 then 1 else 10 * pow10Int(k - 1)
|
|
492
|
+
|
|
493
|
+
# 10^k as a Float, exact for 0 <= k <= 22.
|
|
494
|
+
fun pow10Exact(k: Int) -> Float = match k
|
|
495
|
+
0 => 1.0
|
|
496
|
+
1 => 10.0
|
|
497
|
+
2 => 100.0
|
|
498
|
+
3 => 1000.0
|
|
499
|
+
4 => 10000.0
|
|
500
|
+
5 => 100000.0
|
|
501
|
+
6 => 1000000.0
|
|
502
|
+
7 => 10000000.0
|
|
503
|
+
8 => 100000000.0
|
|
504
|
+
9 => 1000000000.0
|
|
505
|
+
10 => 10000000000.0
|
|
506
|
+
11 => 100000000000.0
|
|
507
|
+
12 => 1000000000000.0
|
|
508
|
+
13 => 10000000000000.0
|
|
509
|
+
14 => 100000000000000.0
|
|
510
|
+
15 => 1000000000000000.0
|
|
511
|
+
16 => 10000000000000000.0
|
|
512
|
+
17 => 100000000000000000.0
|
|
513
|
+
18 => 1000000000000000000.0
|
|
514
|
+
19 => 10000000000000000000.0
|
|
515
|
+
20 => 100000000000000000000.0
|
|
516
|
+
21 => 1000000000000000000000.0
|
|
517
|
+
_ => 10000000000000000000000.0
|
|
518
|
+
|
|
519
|
+
# x * 10^k, approximately (a few ulps), for any k: in steps that stay in Float's range.
|
|
520
|
+
fun scaleApprox(x: Float, k: Int) -> Float =
|
|
521
|
+
if k > 22
|
|
522
|
+
scaleApprox(x * 1e22, k - 22)
|
|
523
|
+
else if k >= 0
|
|
524
|
+
x * pow10Exact(k)
|
|
525
|
+
else if k < -22
|
|
526
|
+
scaleApprox(x / 1e22, k + 22)
|
|
527
|
+
else
|
|
528
|
+
x / pow10Exact(0 - k)
|
std/Float.plum
CHANGED
|
@@ -3,7 +3,7 @@ module std
|
|
|
3
3
|
import std/Str
|
|
4
4
|
import std/Int
|
|
5
5
|
import std/math/math
|
|
6
|
-
import std/
|
|
6
|
+
import std/Decimal
|
|
7
7
|
import std/Option
|
|
8
8
|
import std/Result
|
|
9
9
|
import std/Array
|
|
@@ -31,11 +31,11 @@ primitive Float =
|
|
|
31
31
|
|
|
32
32
|
# Parses a decimal float: an optional leading `+`/`-`, digits with an optional `.`
|
|
33
33
|
# (digits on at least one side), and an optional exponent (`1e5`, `2.5E-3`). The result
|
|
34
|
-
# is the Float nearest the decimal's exact value (std/
|
|
34
|
+
# is the Float nearest the decimal's exact value (std/Decimal), so `Float.parse("0.3")`
|
|
35
35
|
# is `0.3`; past Float's range it is an infinity, and below it a zero.
|
|
36
36
|
fun parse(s: Str) -> Result[Float, NumError] =
|
|
37
|
-
match
|
|
37
|
+
match Decimal.parse(s)
|
|
38
|
-
Some(
|
|
38
|
+
Some(d) => Ok(d.toFloat())
|
|
39
39
|
None => Err(BadNumStr)
|
|
40
40
|
|
|
41
41
|
# The 64 IEEE 754 bits of `self` as an Int (wasm's `i64.reinterpret_f64`): the sign bit is
|
|
@@ -206,16 +206,17 @@ primitive Float =
|
|
|
206
206
|
# Rounded to 6 fractional digits, with trailing zeros trimmed (but always
|
|
207
207
|
# at least one digit after the point, e.g. `3.0` not `3.`). From 2^63 up (past Int's
|
|
208
208
|
# range, and always whole) it is the exact decimal value of the float: `1.0e20` is
|
|
209
|
-
# `100000000000000000000.0`, `1.0e300` the 301 digits of the double nearest 10^300
|
|
209
|
+
# `100000000000000000000.0`, `1.0e300` the 301 digits of the double nearest 10^300
|
|
210
|
+
# (`Decimal.exact`).
|
|
210
211
|
fun toStr(self) -> Str =
|
|
211
212
|
if self != self
|
|
212
213
|
"NaN"
|
|
213
214
|
else if self > Float.Max || self < -Float.Max
|
|
214
215
|
if self < 0.0f then "-Infinity" else "Infinity"
|
|
215
216
|
else if self >= 9223372036854775808.0f || self <= -9223372036854775808.0f
|
|
216
|
-
|
|
217
|
+
d := Decimal.exact(self)
|
|
217
|
-
s :=
|
|
218
|
+
s := d.digits + "0".repeat(d.exp) + ".0"
|
|
218
|
-
if
|
|
219
|
+
if d.neg then "-" + s else s
|
|
219
220
|
else
|
|
220
221
|
neg := self < 0.0f
|
|
221
222
|
abs_val := if neg then -self else self
|
|
@@ -227,39 +228,3 @@ primitive Float =
|
|
|
227
228
|
frac := if carry then 0 else scaled
|
|
228
229
|
s := Int.intToStr(whole_part) + "." + Int.trimmedFracDigits(frac, 6)
|
|
229
230
|
if neg then "-" + s else s
|
|
230
|
-
|
|
231
|
-
# The decimal digits of `m * 2^s` (0 < m < 2^53, s >= 0), exactly: base-10^9 limbs, least
|
|
232
|
-
# significant first (Float.Max needs 35), multiplied up by 2^29 at a time.
|
|
233
|
-
fun bigWholeToStr(m: Int, s: Int) -> Str =
|
|
234
|
-
limbs := Array.filled(36, 0)
|
|
235
|
-
limbs.set(0, m % 1000000000)
|
|
236
|
-
limbs.set(1, m / 1000000000)
|
|
237
|
-
used := bigShift(limbs, if m >= 1000000000 then 2 else 1, s)
|
|
238
|
-
Int.intToStr(limbs.get(used - 1)) + bigLimbsToStr(limbs, used - 2)
|
|
239
|
-
|
|
240
|
-
# Multiplies the limbs by 2^s; returns how many are used.
|
|
241
|
-
fun bigShift(limbs: Array[Int], used: Int, s: Int) -> Int =
|
|
242
|
-
if s <= 0
|
|
243
|
-
used
|
|
244
|
-
else
|
|
245
|
-
k := if s > 29 then 29 else s
|
|
246
|
-
bigShift(limbs, bigMul(limbs, 0, used, 1 << k, 0), s - k)
|
|
247
|
-
|
|
248
|
-
# limbs[i..used) times f (at most 2^29) plus `carry`; returns the new used count.
|
|
249
|
-
fun bigMul(limbs: Array[Int], i: Int, used: Int, f: Int, carry: Int) -> Int =
|
|
250
|
-
if i < used
|
|
251
|
-
p := limbs.get(i) * f + carry
|
|
252
|
-
limbs.set(i, p % 1000000000)
|
|
253
|
-
bigMul(limbs, i + 1, used, f, p / 1000000000)
|
|
254
|
-
else if carry > 0
|
|
255
|
-
limbs.set(used, carry)
|
|
256
|
-
used + 1
|
|
257
|
-
else
|
|
258
|
-
used
|
|
259
|
-
|
|
260
|
-
# Limbs i down to 0, nine digits each.
|
|
261
|
-
fun bigLimbsToStr(limbs: Array[Int], i: Int) -> Str =
|
|
262
|
-
if i < 0
|
|
263
|
-
""
|
|
264
|
-
else
|
|
265
|
-
Int.fixedFracDigits(limbs.get(i), 100000000) + bigLimbsToStr(limbs, i - 1)
|
std/decimal.plum
DELETED
|
@@ -1,436 +0,0 @@
|
|
|
1
|
-
module std
|
|
2
|
-
|
|
3
|
-
import std/Int
|
|
4
|
-
import std/Float
|
|
5
|
-
import std/Str
|
|
6
|
-
import std/Buffer
|
|
7
|
-
import std/Byte
|
|
8
|
-
import std/Slice
|
|
9
|
-
import std/Option
|
|
10
|
-
import std/math/math
|
|
11
|
-
|
|
12
|
-
# Exact conversion between decimal text and Float, on small unsigned big integers.
|
|
13
|
-
#
|
|
14
|
-
# - `decimal.parse(text)` reads `[+-]digits[.digits][(e|E)[+-]digits]` (digits on at least
|
|
15
|
-
# one side of the point) as the Float nearest its exact value, ties to even, as IEEE 754
|
|
16
|
-
# and every correct `strtod` give: `0.3` is the Float literal `0.3`, `1e400` is Infinity,
|
|
17
|
-
# `1e-400` is 0.0. Up to 15 digits and a power of ten up to 22 it is one Float multiply
|
|
18
|
-
# or divide (both exact operands, so rounded once); otherwise a Float estimate is stepped
|
|
19
|
-
# to the nearest Float by comparing the exact value with the halfway points between
|
|
20
|
-
# Floats in big integer arithmetic.
|
|
21
|
-
# - `decimal.shortest(x)` is the shortest digits that parse back to `x` (Burger and Dybvig's
|
|
22
|
-
# free-format algorithm, exact in big integers), and `decimal.format(x)` writes them the
|
|
23
|
-
# way JavaScript's `String(x)` does: `0.1`, `123`, `1e+21`, `1.5e-7`.
|
|
24
|
-
#
|
|
25
|
-
# A big integer is a `Slice[Int]` of 28-bit limbs, least significant first, with no zero
|
|
26
|
-
# limb on top (zero is the empty slice). Products of two limbs fit an Int with room for a
|
|
27
|
-
# carry.
|
|
28
|
-
|
|
29
|
-
LimbBits = 28
|
|
30
|
-
LimbMask = 0xFFF_FFFF
|
|
31
|
-
|
|
32
|
-
# ---- big integers ----
|
|
33
|
-
|
|
34
|
-
fun bigOf(n: Int) -> Slice[Int] =
|
|
35
|
-
out := Slice[Int]()
|
|
36
|
-
pushLimbs(out, n)
|
|
37
|
-
out
|
|
38
|
-
|
|
39
|
-
# Appends the limbs of `n` (n >= 0) on top of `out`.
|
|
40
|
-
fun pushLimbs(out: Slice[Int], n: Int) -> Unit =
|
|
41
|
-
if n > 0
|
|
42
|
-
out.push(n & LimbMask)
|
|
43
|
-
pushLimbs(out, n >> LimbBits)
|
|
44
|
-
|
|
45
|
-
fun bigCopy(a: Slice[Int]) -> Slice[Int] = a.sublist(0, a.length())
|
|
46
|
-
|
|
47
|
-
# `a = a * f + add` in place, for 0 < f < 2^28 and 0 <= add < 2^28.
|
|
48
|
-
fun bigMulAdd(a: Slice[Int], f: Int, add: Int) -> Unit =
|
|
49
|
-
pushLimbs(a, mulAddFrom(a, f, 0, add))
|
|
50
|
-
|
|
51
|
-
fun mulAddFrom(a: Slice[Int], f: Int, i: Int, carry: Int) -> Int =
|
|
52
|
-
if i >= a.length()
|
|
53
|
-
carry
|
|
54
|
-
else
|
|
55
|
-
p := a.atUnchecked(i) * f + carry
|
|
56
|
-
a.putAt(i, p & LimbMask)
|
|
57
|
-
mulAddFrom(a, f, i + 1, p >> LimbBits)
|
|
58
|
-
|
|
59
|
-
# `a * 5^k`, in place.
|
|
60
|
-
fun bigMulPow5(a: Slice[Int], k: Int) -> Unit =
|
|
61
|
-
if k >= 12
|
|
62
|
-
bigMulAdd(a, 244140625, 0)
|
|
63
|
-
bigMulPow5(a, k - 12)
|
|
64
|
-
else if k > 0
|
|
65
|
-
bigMulAdd(a, pow5(k), 0)
|
|
66
|
-
|
|
67
|
-
fun pow5(k: Int) -> Int = if k <= 0 then 1 else 5 * pow5(k - 1)
|
|
68
|
-
|
|
69
|
-
# A new big integer: `a * 2^k` (k >= 0).
|
|
70
|
-
fun bigShl(a: Slice[Int], k: Int) -> Slice[Int] =
|
|
71
|
-
if a.isEmpty() || k == 0
|
|
72
|
-
bigCopy(a)
|
|
73
|
-
else
|
|
74
|
-
b := bigCopy(a)
|
|
75
|
-
bigMulAdd(b, 1 << {k % LimbBits}, 0)
|
|
76
|
-
out := Slice[Int]()
|
|
77
|
-
for _ := range k / LimbBits
|
|
78
|
-
out.push(0)
|
|
79
|
-
out.add(b)
|
|
80
|
-
out
|
|
81
|
-
|
|
82
|
-
# A new big integer: `a * 10^k` (k >= 0).
|
|
83
|
-
fun bigMulPow10(a: Slice[Int], k: Int) -> Slice[Int] =
|
|
84
|
-
b := bigCopy(a)
|
|
85
|
-
bigMulPow5(b, k)
|
|
86
|
-
bigShl(b, k)
|
|
87
|
-
|
|
88
|
-
# -1, 0 or 1 as `a` is below, equal to or above `b`.
|
|
89
|
-
fun bigCmp(a: Slice[Int], b: Slice[Int]) -> Int =
|
|
90
|
-
if a.length() != b.length()
|
|
91
|
-
if a.length() < b.length() then -1 else 1
|
|
92
|
-
else
|
|
93
|
-
cmpFrom(a, b, a.length() - 1)
|
|
94
|
-
|
|
95
|
-
fun cmpFrom(a: Slice[Int], b: Slice[Int], i: Int) -> Int =
|
|
96
|
-
if i < 0
|
|
97
|
-
0
|
|
98
|
-
else
|
|
99
|
-
x := a.atUnchecked(i)
|
|
100
|
-
y := b.atUnchecked(i)
|
|
101
|
-
if x != y
|
|
102
|
-
if x < y then -1 else 1
|
|
103
|
-
else
|
|
104
|
-
cmpFrom(a, b, i - 1)
|
|
105
|
-
|
|
106
|
-
# A new big integer: `a + b`.
|
|
107
|
-
fun bigAdd(a: Slice[Int], b: Slice[Int]) -> Slice[Int] =
|
|
108
|
-
out := Slice[Int]()
|
|
109
|
-
n := if a.length() > b.length() then a.length() else b.length()
|
|
110
|
-
addFrom(a, b, out, 0, n, 0)
|
|
111
|
-
out
|
|
112
|
-
|
|
113
|
-
fun addFrom(a: Slice[Int], b: Slice[Int], out: Slice[Int], i: Int, n: Int, carry: Int) -> Unit =
|
|
114
|
-
if i < n
|
|
115
|
-
s := limbAt(a, i) + limbAt(b, i) + carry
|
|
116
|
-
out.push(s & LimbMask)
|
|
117
|
-
addFrom(a, b, out, i + 1, n, s >> LimbBits)
|
|
118
|
-
else if carry > 0
|
|
119
|
-
out.push(carry)
|
|
120
|
-
|
|
121
|
-
# A new big integer: `a - b`, for a >= b.
|
|
122
|
-
fun bigSub(a: Slice[Int], b: Slice[Int]) -> Slice[Int] =
|
|
123
|
-
out := Slice[Int]()
|
|
124
|
-
subFrom(a, b, out, 0, 0)
|
|
125
|
-
trimTop(out)
|
|
126
|
-
out
|
|
127
|
-
|
|
128
|
-
fun subFrom(a: Slice[Int], b: Slice[Int], out: Slice[Int], i: Int, borrow: Int) -> Unit =
|
|
129
|
-
if i < a.length()
|
|
130
|
-
d := a.atUnchecked(i) - limbAt(b, i) - borrow
|
|
131
|
-
out.push(if d < 0 then d + {1 << LimbBits} else d)
|
|
132
|
-
subFrom(a, b, out, i + 1, if d < 0 then 1 else 0)
|
|
133
|
-
|
|
134
|
-
fun limbAt(a: Slice[Int], i: Int) -> Int = if i < a.length() then a.atUnchecked(i) else 0
|
|
135
|
-
|
|
136
|
-
# Drops zero limbs from the top.
|
|
137
|
-
fun trimTop(a: Slice[Int]) -> Unit =
|
|
138
|
-
if a.length() > 0 && a.atUnchecked(a.length() - 1) == 0
|
|
139
|
-
_ := a.pop()
|
|
140
|
-
trimTop(a)
|
|
141
|
-
|
|
142
|
-
# The big integer of the decimal digits `ds[i..j)`, eight digits per step.
|
|
143
|
-
fun bigOfDigits(ds: Str, i: Int, j: Int, acc: Slice[Int]) -> Slice[Int] =
|
|
144
|
-
if i >= j
|
|
145
|
-
acc
|
|
146
|
-
else
|
|
147
|
-
k := if j - i < 8 then j - i else 8
|
|
148
|
-
v := digitsValue(ds, i, i + k, 0)
|
|
149
|
-
bigMulAdd(acc, pow10Int(k), 0)
|
|
150
|
-
bigAddSmall(acc, v)
|
|
151
|
-
bigOfDigits(ds, i + k, j, acc)
|
|
152
|
-
|
|
153
|
-
# `a + v` in place, for 0 <= v < 2^28.
|
|
154
|
-
fun bigAddSmall(a: Slice[Int], v: Int) -> Unit =
|
|
155
|
-
pushLimbs(a, addSmallFrom(a, 0, v))
|
|
156
|
-
|
|
157
|
-
fun addSmallFrom(a: Slice[Int], i: Int, carry: Int) -> Int =
|
|
158
|
-
if carry == 0 || i >= a.length()
|
|
159
|
-
carry
|
|
160
|
-
else
|
|
161
|
-
s := a.atUnchecked(i) + carry
|
|
162
|
-
a.putAt(i, s & LimbMask)
|
|
163
|
-
addSmallFrom(a, i + 1, s >> LimbBits)
|
|
164
|
-
|
|
165
|
-
fun digitsValue(ds: Str, i: Int, j: Int, acc: Int) -> Int =
|
|
166
|
-
if i >= j then acc else digitsValue(ds, i + 1, j, acc * 10 + ds.byteAtUnchecked(i) - 48)
|
|
167
|
-
|
|
168
|
-
fun pow10Int(k: Int) -> Int = if k <= 0 then 1 else 10 * pow10Int(k - 1)
|
|
169
|
-
|
|
170
|
-
# 10^k as a Float, exact for 0 <= k <= 22.
|
|
171
|
-
fun pow10Exact(k: Int) -> Float = match k
|
|
172
|
-
0 => 1.0
|
|
173
|
-
1 => 10.0
|
|
174
|
-
2 => 100.0
|
|
175
|
-
3 => 1000.0
|
|
176
|
-
4 => 10000.0
|
|
177
|
-
5 => 100000.0
|
|
178
|
-
6 => 1000000.0
|
|
179
|
-
7 => 10000000.0
|
|
180
|
-
8 => 100000000.0
|
|
181
|
-
9 => 1000000000.0
|
|
182
|
-
10 => 10000000000.0
|
|
183
|
-
11 => 100000000000.0
|
|
184
|
-
12 => 1000000000000.0
|
|
185
|
-
13 => 10000000000000.0
|
|
186
|
-
14 => 100000000000000.0
|
|
187
|
-
15 => 1000000000000000.0
|
|
188
|
-
16 => 10000000000000000.0
|
|
189
|
-
17 => 100000000000000000.0
|
|
190
|
-
18 => 1000000000000000000.0
|
|
191
|
-
19 => 10000000000000000000.0
|
|
192
|
-
20 => 100000000000000000000.0
|
|
193
|
-
21 => 1000000000000000000000.0
|
|
194
|
-
_ => 10000000000000000000000.0
|
|
195
|
-
|
|
196
|
-
# x * 10^k, approximately (a few ulps), for any k: in steps that stay in Float's range.
|
|
197
|
-
fun scaleApprox(x: Float, k: Int) -> Float =
|
|
198
|
-
if k > 22
|
|
199
|
-
scaleApprox(x * 1e22, k - 22)
|
|
200
|
-
else if k >= 0
|
|
201
|
-
x * pow10Exact(k)
|
|
202
|
-
else if k < -22
|
|
203
|
-
scaleApprox(x / 1e22, k + 22)
|
|
204
|
-
else
|
|
205
|
-
x / pow10Exact(0 - k)
|
|
206
|
-
|
|
207
|
-
# ---- decimal text to Float ----
|
|
208
|
-
|
|
209
|
-
# What `parse` reads off the text: the significant digits (no point), the power of ten they
|
|
210
|
-
# are scaled by, the sign, and whether the text was a number at all.
|
|
211
|
-
struct Scan(mut digits: Buffer, mut exp: Int, mut neg: Bool, mut ok: Bool, mut seen: Int, mut pos: Int)
|
|
212
|
-
|
|
213
|
-
# The Float nearest the decimal `text`, or None if it isn't one (see the top of the file).
|
|
214
|
-
fun parse(text: Str) -> Option[Float] =
|
|
215
|
-
sc := Scan(digits: Buffer(), exp: 0, neg: false, ok: true, seen: 0, pos: 0)
|
|
216
|
-
n := text.length()
|
|
217
|
-
if n > 0 && {text.byteAt(0) == 45 || text.byteAt(0) == 43}
|
|
218
|
-
sc.neg = text.byteAt(0) == 45
|
|
219
|
-
sc.pos = 1
|
|
220
|
-
scanDigits(text, sc, false)
|
|
221
|
-
if sc.pos < n && text.byteAt(sc.pos) == 46
|
|
222
|
-
sc.pos = sc.pos + 1
|
|
223
|
-
scanDigits(text, sc, true)
|
|
224
|
-
if sc.seen == 0
|
|
225
|
-
sc.ok = false
|
|
226
|
-
if sc.ok && sc.pos < n && {text.byteAt(sc.pos) == 101 || text.byteAt(sc.pos) == 69}
|
|
227
|
-
sc.pos = sc.pos + 1
|
|
228
|
-
eneg := sc.pos < n && text.byteAt(sc.pos) == 45
|
|
229
|
-
if sc.pos < n && {text.byteAt(sc.pos) == 45 || text.byteAt(sc.pos) == 43}
|
|
230
|
-
sc.pos = sc.pos + 1
|
|
231
|
-
start := sc.pos
|
|
232
|
-
e := expDigits(text, sc, 0)
|
|
233
|
-
if sc.pos == start
|
|
234
|
-
sc.ok = false
|
|
235
|
-
sc.exp = sc.exp + {if eneg then 0 - e else e}
|
|
236
|
-
if !sc.ok || sc.pos != n
|
|
237
|
-
None
|
|
238
|
-
else
|
|
239
|
-
v := toFloat(sc.digits.toStr(), sc.exp)
|
|
240
|
-
Some(if sc.neg then -v else v)
|
|
241
|
-
|
|
242
|
-
# Reads digits from `sc.pos` on into `sc.digits` (leading zeros of the number skipped); a
|
|
243
|
-
# digit after the point lowers the exponent by one.
|
|
244
|
-
fun scanDigits(text: Str, sc: Scan, frac: Bool) -> Unit =
|
|
245
|
-
if sc.pos < text.length()
|
|
246
|
-
b := text.byteAtUnchecked(sc.pos)
|
|
247
|
-
if b >= 48 && b <= 57
|
|
248
|
-
if b != 48 || sc.digits.length() > 0
|
|
249
|
-
sc.digits.writeByte(Byte(b))
|
|
250
|
-
if frac
|
|
251
|
-
sc.exp = sc.exp - 1
|
|
252
|
-
sc.seen = sc.seen + 1
|
|
253
|
-
sc.pos = sc.pos + 1
|
|
254
|
-
scanDigits(text, sc, frac)
|
|
255
|
-
|
|
256
|
-
# The exponent's digits from `sc.pos` on, held at a million (far past any Float).
|
|
257
|
-
fun expDigits(text: Str, sc: Scan, acc: Int) -> Int =
|
|
258
|
-
if sc.pos < text.length() && text.byteAtUnchecked(sc.pos) >= 48 && text.byteAtUnchecked(sc.pos) <= 57
|
|
259
|
-
d := text.byteAtUnchecked(sc.pos) - 48
|
|
260
|
-
sc.pos = sc.pos + 1
|
|
261
|
-
expDigits(text, sc, if acc > 1000000 then acc else acc * 10 + d)
|
|
262
|
-
else
|
|
263
|
-
acc
|
|
264
|
-
|
|
265
|
-
# The Float nearest `digits * 10^exp`, for a string of decimal digits (zeros allowed at
|
|
266
|
-
# either end, or none at all: zero).
|
|
267
|
-
fun toFloat(digits: Str, exp: Int) -> Float =
|
|
268
|
-
a := firstNonZero(digits, 0)
|
|
269
|
-
if a >= digits.length()
|
|
270
|
-
0.0
|
|
271
|
-
else
|
|
272
|
-
b := lastNonZero(digits, digits.length() - 1)
|
|
273
|
-
ds := digits.sub(a, b + 1)
|
|
274
|
-
e := exp + {digits.length() - 1 - b}
|
|
275
|
-
n := ds.length()
|
|
276
|
-
if n + e > 310
|
|
277
|
-
1.0 / 0.0
|
|
278
|
-
else if n + e < -324
|
|
279
|
-
0.0
|
|
280
|
-
else if n <= 15 && e >= -22 && e <= 22
|
|
281
|
-
m := Float(digitsValue(ds, 0, n, 0))
|
|
282
|
-
if e >= 0 then m * pow10Exact(e) else m / pow10Exact(0 - e)
|
|
283
|
-
else
|
|
284
|
-
k := if n < 18 then n else 18
|
|
285
|
-
guess := scaleApprox(Float(digitsValue(ds, 0, k, 0)), e + n - k)
|
|
286
|
-
big := bigOfDigits(ds, 0, n, Slice[Int]())
|
|
287
|
-
left := if e >= 0 then bigMulPow10(big, e) else big
|
|
288
|
-
nearest(left, if e >= 0 then 0 else e, guess)
|
|
289
|
-
|
|
290
|
-
fun firstNonZero(s: Str, i: Int) -> Int =
|
|
291
|
-
if i < s.length() && s.byteAtUnchecked(i) == 48 then firstNonZero(s, i + 1) else i
|
|
292
|
-
|
|
293
|
-
fun lastNonZero(s: Str, i: Int) -> Int =
|
|
294
|
-
if i > 0 && s.byteAtUnchecked(i) == 48 then lastNonZero(s, i - 1) else i
|
|
295
|
-
|
|
296
|
-
# The exact value is `left * 10^e` (e <= 0; with e = 0 `left` already holds the whole
|
|
297
|
-
# value). Steps `z` one Float at a time until it is the one nearest that value.
|
|
298
|
-
fun nearest(left: Slice[Int], e: Int, z: Float) -> Float =
|
|
299
|
-
if z > Float.Max
|
|
300
|
-
z
|
|
301
|
-
else
|
|
302
|
-
bits := z.toBits()
|
|
303
|
-
expo := {bits >> 52} & 0x7FF
|
|
304
|
-
frac := bits & 0xF_FFFF_FFFF_FFFF
|
|
305
|
-
mz := if expo == 0 then frac else frac | 0x10_0000_0000_0000
|
|
306
|
-
ez := if expo == 0 then -1074 else expo - 1075
|
|
307
|
-
up := cmpExact(left, e, 2 * mz + 1, ez - 1)
|
|
308
|
-
if up > 0
|
|
309
|
-
nearest(left, e, Float.fromBits(bits + 1))
|
|
310
|
-
else if up == 0
|
|
311
|
-
if mz % 2 == 0 then z else Float.fromBits(bits + 1)
|
|
312
|
-
else if mz == 0
|
|
313
|
-
z
|
|
314
|
-
else
|
|
315
|
-
down := if frac == 0 && expo > 1 then cmpExact(left, e, 4 * mz - 1, ez - 2) else cmpExact(left, e, 2 * mz - 1, ez - 1)
|
|
316
|
-
if down < 0
|
|
317
|
-
nearest(left, e, Float.fromBits(bits - 1))
|
|
318
|
-
else if down == 0
|
|
319
|
-
if mz % 2 == 0 then z else Float.fromBits(bits - 1)
|
|
320
|
-
else
|
|
321
|
-
z
|
|
322
|
-
|
|
323
|
-
# The sign of `left * 10^e - m * 2^s`, exactly (e <= 0, m > 0).
|
|
324
|
-
fun cmpExact(left: Slice[Int], e: Int, m: Int, s: Int) -> Int =
|
|
325
|
-
right := bigOf(m)
|
|
326
|
-
bigMulPow5(right, 0 - e)
|
|
327
|
-
# left * 2^e against right * 2^s.
|
|
328
|
-
d := e - s
|
|
329
|
-
if d >= 0 then bigCmp(bigShl(left, d), right) else bigCmp(left, bigShl(right, 0 - d))
|
|
330
|
-
|
|
331
|
-
# ---- Float to the shortest decimal ----
|
|
332
|
-
|
|
333
|
-
# The shortest digits of `x` that parse back to it, with `point`, their decimal exponent:
|
|
334
|
-
# x = 0.d1d2...dn * 10^point. `x` must be finite and above 0.
|
|
335
|
-
struct Digits(digits: Str, point: Int)
|
|
336
|
-
|
|
337
|
-
fun shortest(x: Float) -> Digits =
|
|
338
|
-
bits := x.toBits()
|
|
339
|
-
expo := {bits >> 52} & 0x7FF
|
|
340
|
-
frac := bits & 0xF_FFFF_FFFF_FFFF
|
|
341
|
-
f := if expo == 0 then frac else frac | 0x10_0000_0000_0000
|
|
342
|
-
e := if expo == 0 then -1074 else expo - 1075
|
|
343
|
-
even := f % 2 == 0
|
|
344
|
-
# Twice the value and the gaps to the neighbouring Floats, as r / s, mp / s and mm / s.
|
|
345
|
-
lowGap := frac == 0 && expo > 1
|
|
346
|
-
r0 := if e >= 0
|
|
347
|
-
if lowGap then bigShl(bigOf(f), e + 2) else bigShl(bigOf(f), e + 1)
|
|
348
|
-
else
|
|
349
|
-
if lowGap then bigOf(4 * f) else bigOf(2 * f)
|
|
350
|
-
s0 := if e >= 0
|
|
351
|
-
if lowGap then bigOf(4) else bigOf(2)
|
|
352
|
-
else
|
|
353
|
-
if lowGap then bigShl(bigOf(1), 2 - e) else bigShl(bigOf(1), 1 - e)
|
|
354
|
-
mp0 := if e >= 0
|
|
355
|
-
if lowGap then bigShl(bigOf(1), e + 1) else bigShl(bigOf(1), e)
|
|
356
|
-
else
|
|
357
|
-
if lowGap then bigOf(2) else bigOf(1)
|
|
358
|
-
mm0 := if e >= 0 then bigShl(bigOf(1), e) else bigOf(1)
|
|
359
|
-
bitLen := 64 - f.leadingZeros()
|
|
360
|
-
k := Int({Float(e + bitLen - 1) * 0.30102999566398114 - 0.0000000001}.ceil())
|
|
361
|
-
r := if k >= 0 then r0 else bigMulPow10(r0, 0 - k)
|
|
362
|
-
s := if k >= 0 then bigMulPow10(s0, k) else s0
|
|
363
|
-
mp := if k >= 0 then mp0 else bigMulPow10(mp0, 0 - k)
|
|
364
|
-
mm := if k >= 0 then mm0 else bigMulPow10(mm0, 0 - k)
|
|
365
|
-
high := bigCmp(bigAdd(r, mp), s)
|
|
366
|
-
out := Buffer()
|
|
367
|
-
if high > 0 || even && high == 0
|
|
368
|
-
generate(r, s, mp, mm, even, out)
|
|
369
|
-
Digits(digits: out.toStr(), point: k + 1)
|
|
370
|
-
else
|
|
371
|
-
generate(bigMulPow10(r, 1), s, bigMulPow10(mp, 1), bigMulPow10(mm, 1), even, out)
|
|
372
|
-
Digits(digits: out.toStr(), point: k)
|
|
373
|
-
|
|
374
|
-
# Writes the digits of r / s into `out` until the digits so far are within the gaps
|
|
375
|
-
# (inclusive when `even`: a tie parses to the even Float, which is `x`).
|
|
376
|
-
fun generate(r: Slice[Int], s: Slice[Int], mp: Slice[Int], mm: Slice[Int], even: Bool, out: Buffer) -> Unit =
|
|
377
|
-
q := quotientDigit(r, s, 0)
|
|
378
|
-
rest := q.second
|
|
379
|
-
d := q.first
|
|
380
|
-
low := bigCmp(rest, mm)
|
|
381
|
-
tc1 := low < 0 || even && low == 0
|
|
382
|
-
high := bigCmp(bigAdd(rest, mp), s)
|
|
383
|
-
tc2 := high > 0 || even && high == 0
|
|
384
|
-
if !tc1 && !tc2
|
|
385
|
-
out.writeByte(Byte(48 + d))
|
|
386
|
-
generate(bigMulPow10(rest, 1), s, bigMulPow10(mp, 1), bigMulPow10(mm, 1), even, out)
|
|
387
|
-
else if tc1 && !tc2
|
|
388
|
-
out.writeByte(Byte(48 + d))
|
|
389
|
-
else if !tc1 && tc2
|
|
390
|
-
out.writeByte(Byte(49 + d))
|
|
391
|
-
else
|
|
392
|
-
half := bigCmp(bigShl(rest, 1), s)
|
|
393
|
-
out.writeByte(Byte(if half < 0 then 48 + d else 49 + d))
|
|
394
|
-
|
|
395
|
-
struct QR(first: Int, second: Slice[Int])
|
|
396
|
-
|
|
397
|
-
# r / s as a digit 0..9 and the remainder, by subtracting (r < 10 s).
|
|
398
|
-
fun quotientDigit(r: Slice[Int], s: Slice[Int], d: Int) -> QR =
|
|
399
|
-
if bigCmp(r, s) < 0 then QR(first: d, second: r) else quotientDigit(bigSub(r, s), s, d + 1)
|
|
400
|
-
|
|
401
|
-
# `x` as JavaScript's `String(x)` writes it (and JSON with it): the shortest digits that
|
|
402
|
-
# parse back to `x`, in plain notation from 1e-6 up to 1e21 (`0.000001`, `123.5`,
|
|
403
|
-
# `100000000000000000000`) and in exponent notation outside it (`1e+21`, `1.5e-7`). `-0`
|
|
404
|
-
# for minus zero, `NaN`, `Infinity` and `-Infinity` for the rest.
|
|
405
|
-
fun format(x: Float) -> Str =
|
|
406
|
-
if x != x
|
|
407
|
-
"NaN"
|
|
408
|
-
else if x > Float.Max
|
|
409
|
-
"Infinity"
|
|
410
|
-
else if x < 0.0 - Float.Max
|
|
411
|
-
"-Infinity"
|
|
412
|
-
else if x == 0.0
|
|
413
|
-
if 1.0 / x < 0.0 then "-0" else "0"
|
|
414
|
-
else if x < 0.0
|
|
415
|
-
"-" + formatPositive(0.0 - x)
|
|
416
|
-
else
|
|
417
|
-
formatPositive(x)
|
|
418
|
-
|
|
419
|
-
fun formatPositive(x: Float) -> Str =
|
|
420
|
-
if x < 9007199254740992.0 && x.trunc() == x
|
|
421
|
-
Int(x).toStr()
|
|
422
|
-
else
|
|
423
|
-
sh := shortest(x)
|
|
424
|
-
ds := sh.digits
|
|
425
|
-
n := ds.length()
|
|
426
|
-
k := sh.point
|
|
427
|
-
if k >= n && k <= 21
|
|
428
|
-
ds + "0".repeat(k - n)
|
|
429
|
-
else if k > 0 && k <= 21
|
|
430
|
-
ds.sub(0, k) + "." + ds.sub(k, n)
|
|
431
|
-
else if k > -6 && k <= 0
|
|
432
|
-
"0." + "0".repeat(0 - k) + ds
|
|
433
|
-
else
|
|
434
|
-
mant := if n == 1 then ds else ds.sub(0, 1) + "." + ds.sub(1, n)
|
|
435
|
-
x10 := k - 1
|
|
436
|
-
mant + "e" + {if x10 < 0 then "-" else "+"} + {if x10 < 0 then 0 - x10 else x10}.toStr()
|
std/encoding/Json.plum
CHANGED
|
@@ -9,7 +9,7 @@ import std/Str
|
|
|
9
9
|
import std/Buffer
|
|
10
10
|
import std/Option
|
|
11
11
|
import std/Result
|
|
12
|
-
import std/
|
|
12
|
+
import std/Decimal
|
|
13
13
|
|
|
14
14
|
# Placement rule for built-in `toJson` / `fromJson`: they live HERE, in this
|
|
15
15
|
# file, as extension blocks at the bottom (`primitive Int =`, `primitive Slice[T] =`),
|
|
@@ -169,7 +169,7 @@ enum Json =
|
|
|
169
169
|
# JavaScript writes them (`123`, `0.1`, `1e+21`, `1.5e-7`). JSON has no NaN or Infinity,
|
|
170
170
|
# so those are written `null`, as `JSON.stringify` does.
|
|
171
171
|
fun numberText(x: Float) -> Str =
|
|
172
|
-
if x != x || x > Float.Max || x < 0.0 - Float.Max then "null" else
|
|
172
|
+
if x != x || x > Float.Max || x < 0.0 - Float.Max then "null" else Decimal.ofFloat(x).toStr()
|
|
173
173
|
|
|
174
174
|
fun escapeJsonStr(s: Str) -> Str =
|
|
175
175
|
buf := Buffer()
|
|
@@ -313,7 +313,7 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
|
|
|
313
313
|
Ok(value)
|
|
314
314
|
|
|
315
315
|
# `-?(0|[1-9][0-9]*)(.[0-9]+)?([eE][+-]?[0-9]+)?`: a leading zero stands alone. The value
|
|
316
|
-
# is the Float nearest the number (std/
|
|
316
|
+
# is the Float nearest the number (std/Decimal), and one past Float's range is an error,
|
|
317
317
|
# since JSON has no Infinity.
|
|
318
318
|
fun parseNumber(self) -> Result[Json, JsonError] =
|
|
319
319
|
start := self.pos
|
|
@@ -360,7 +360,7 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
|
|
|
360
360
|
self.numberOf(self.src.sub(start, self.pos))
|
|
361
361
|
|
|
362
362
|
fun numberOf(self, text: Str) -> Result[Json, JsonError] =
|
|
363
|
-
match
|
|
363
|
+
match Decimal.parse(text).map(|d| d.toFloat())
|
|
364
364
|
Some(f) =>
|
|
365
365
|
if f > Float.Max || f < 0.0 - Float.Max
|
|
366
366
|
self.note("number out of range")
|
tests/std/Decimal.plum
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
import std/Float
|
|
3
|
+
import std/Str
|
|
4
|
+
import std/Option
|
|
5
|
+
import std/Result
|
|
6
|
+
import std/Decimal
|
|
7
|
+
import std/Pair
|
|
8
|
+
|
|
9
|
+
fun parsed(text: Str) -> Float = Decimal.parse(text)!.toFloat()
|
|
10
|
+
|
|
11
|
+
fun shortText(x: Float) -> Str = Decimal.ofFloat(x).toStr()
|
|
12
|
+
|
|
13
|
+
fun roundTrips(bits: Int) -> Bool =
|
|
14
|
+
x := Float.fromBits(bits & 0x7FFF_FFFF_FFFF_FFFF)
|
|
15
|
+
if x != x || x > Float.Max
|
|
16
|
+
true
|
|
17
|
+
else
|
|
18
|
+
parsed(shortText(x)) == x && parsed(shortText(0.0 - x)) == 0.0 - x && Decimal.exact(x).toFloat() == x && Decimal.exact(0.0 - x).toFloat() == 0.0 - x
|
|
19
|
+
|
|
20
|
+
fun same(d: Decimal, digits: Str, exp: Int, neg: Bool) -> Bool =
|
|
21
|
+
d.digits == digits && d.exp == exp && d.neg == neg
|
|
22
|
+
|
|
23
|
+
test "Decimal.parse is exact: digits, exponent and sign, nothing rounded"
|
|
24
|
+
assert same(Decimal.parse("0.1")!, "1", -1, false)
|
|
25
|
+
assert same(Decimal.parse("-12.50")!, "1250", -2, true)
|
|
26
|
+
assert same(Decimal.parse("+007")!, "7", 0, false)
|
|
27
|
+
assert same(Decimal.parse("1e400")!, "1", 400, false)
|
|
28
|
+
assert same(Decimal.parse("2.5E-3")!, "25", -4, false)
|
|
29
|
+
assert same(Decimal.parse("0.30000000000000000000000000001")!, "30000000000000000000000000001", -29, false)
|
|
30
|
+
assert same(Decimal.parse("0")!, "0", 0, false) && same(Decimal.parse("-0.000")!, "0", 0, true)
|
|
31
|
+
assert same(Decimal.parse("0e5")!, "0", 0, false)
|
|
32
|
+
assert same(Decimal.parse("5.")!, "5", 0, false) && same(Decimal.parse(".5")!, "5", -1, false)
|
|
33
|
+
assert Decimal.parse("0")!.isZero() && !Decimal.parse("0.1")!.isZero()
|
|
34
|
+
|
|
35
|
+
test "Decimal.parse: text that is not a number"
|
|
36
|
+
assert Decimal.parse("x").isNone()
|
|
37
|
+
assert Decimal.parse("").isNone()
|
|
38
|
+
assert Decimal.parse("1e").isNone()
|
|
39
|
+
assert Decimal.parse("1e+").isNone()
|
|
40
|
+
assert Decimal.parse(".").isNone()
|
|
41
|
+
assert Decimal.parse("-").isNone()
|
|
42
|
+
assert Decimal.parse("1.2.3").isNone()
|
|
43
|
+
assert Decimal.parse("12a").isNone()
|
|
44
|
+
assert Decimal.parse(" 1").isNone()
|
|
45
|
+
|
|
46
|
+
test "toFloat: nearest Float, ties to even, edges"
|
|
47
|
+
assert parsed("0.3") == 0.3
|
|
48
|
+
assert parsed("123.456") == 123.456
|
|
49
|
+
assert parsed("0.1234567890123") == 0.1234567890123
|
|
50
|
+
assert parsed("1e400") > Float.Max
|
|
51
|
+
assert parsed("-1e400") < 0.0 - Float.Max
|
|
52
|
+
assert parsed("1e-400") == 0.0
|
|
53
|
+
assert parsed("2.2250738585072014e-308") == 2.2250738585072014e-308
|
|
54
|
+
assert parsed("4.9406564584124654e-324") == 4.9406564584124654e-324
|
|
55
|
+
assert parsed("9007199254740993") == 9007199254740992.0
|
|
56
|
+
assert parsed("9007199254740995") == 9007199254740996.0
|
|
57
|
+
assert parsed("1.7976931348623157e308") == Float.Max
|
|
58
|
+
assert parsed("3.14159265358979") == 3.14159265358979
|
|
59
|
+
assert parsed("1.50") == 1.5 && parsed("-12.50") == -12.5
|
|
60
|
+
assert 1.0 / parsed("-0") < 0.0 && parsed("0") == 0.0
|
|
61
|
+
assert Decimal(digits: "15", exp: -1, neg: false).toFloat() == 1.5
|
|
62
|
+
assert Decimal(digits: "0015000", exp: -4, neg: true).toFloat() == -1.5
|
|
63
|
+
|
|
64
|
+
test "Decimal.ofFloat: the shortest digits that convert back"
|
|
65
|
+
assert same(Decimal.ofFloat(0.1), "1", -1, false)
|
|
66
|
+
assert same(Decimal.ofFloat(-1.5), "15", -1, true)
|
|
67
|
+
assert same(Decimal.ofFloat(123.0), "123", 0, false)
|
|
68
|
+
assert same(Decimal.ofFloat(1200.0), "12", 2, false)
|
|
69
|
+
assert same(Decimal.ofFloat(1e21), "1", 21, false)
|
|
70
|
+
assert same(Decimal.ofFloat(0.1 + 0.2), "30000000000000004", -17, false)
|
|
71
|
+
assert same(Decimal.ofFloat(5e-324), "5", -324, false)
|
|
72
|
+
assert same(Decimal.ofFloat(Float.Max), "17976931348623157", 292, false)
|
|
73
|
+
assert same(Decimal.ofFloat(0.0), "0", 0, false) && same(Decimal.ofFloat(-0.0), "0", 0, true)
|
|
74
|
+
|
|
75
|
+
test "Decimal.exact: the value a Float holds, digit for digit"
|
|
76
|
+
assert same(Decimal.exact(0.5), "5", -1, false)
|
|
77
|
+
assert same(Decimal.exact(-0.375), "375", -3, true)
|
|
78
|
+
assert same(Decimal.exact(3.0), "3", 0, false)
|
|
79
|
+
assert same(Decimal.exact(1e20), "1", 20, false)
|
|
80
|
+
assert same(Decimal.exact(1e23), "99999999999999991611392", 0, false)
|
|
81
|
+
assert Decimal.exact(0.1).toStr() == "0.1000000000000000055511151231257827021181583404541015625"
|
|
82
|
+
assert same(Decimal.exact(5e-324), "4940656458412465441765687928682213723650598026143247644255856825006755072702087518652998363616359923797965646954457177309266567103559397963987747960107818781263007131903114045278458171678489821036887186360569987307230500063874091535649843873124733972731696151400317153853980741262385655911710266585566867681870395603106249319452715914924553293054565444011274801297099995419319894090804165633245247571478690147267801593552386115501348035264934720193790268107107491703332226844753335720832431936092382893458368060106011506169809753078342277318329247904982524730776375927247874656084778203734469699533647017972677717585125660551199131504891101451037862738167250955837389733598993664809941164205702637090279242767544565229087538682506419718265533447265625", -1074, false)
|
|
83
|
+
assert same(Decimal.exact(0.0), "0", 0, false) && same(Decimal.exact(-0.0), "0", 0, true)
|
|
84
|
+
top := Decimal.exact(Float.Max)
|
|
85
|
+
assert top.digits.length() + top.exp == 309 && top.digits.startsWith("179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368")
|
|
86
|
+
assert top.toFloat() == Float.Max
|
|
87
|
+
|
|
88
|
+
test "toStr: plain digits from 1e-6 up to 1e21, exponent notation outside, as JavaScript writes them"
|
|
89
|
+
assert shortText(0.1) == "0.1"
|
|
90
|
+
assert shortText(123.0) == "123"
|
|
91
|
+
assert shortText(0.1234567) == "0.1234567"
|
|
92
|
+
assert shortText(1e21) == "1e+21"
|
|
93
|
+
assert shortText(1e-7) == "1e-7"
|
|
94
|
+
assert shortText(1.5e-7) == "1.5e-7"
|
|
95
|
+
assert shortText(0.000001) == "0.000001"
|
|
96
|
+
assert shortText(Float.Max) == "1.7976931348623157e+308"
|
|
97
|
+
assert shortText(5e-324) == "5e-324"
|
|
98
|
+
assert shortText(0.1 + 0.2) == "0.30000000000000004"
|
|
99
|
+
assert shortText(-1.5) == "-1.5"
|
|
100
|
+
assert shortText(1e20) == "100000000000000000000"
|
|
101
|
+
assert shortText(123456.789) == "123456.789"
|
|
102
|
+
assert shortText(9007199254740991.0) == "9007199254740991"
|
|
103
|
+
assert shortText(0.0) == "0" && shortText(-0.0) == "-0"
|
|
104
|
+
assert Decimal.parse("1.50")!.toStr() == "1.50" && Decimal.parse("-12e3")!.toStr() == "-12000"
|
|
105
|
+
assert Decimal.parse("1234567890123456789012345")!.toStr() == "1.234567890123456789012345e+24"
|
|
106
|
+
assert Decimal.parse("0.00000012")!.toStr() == "1.2e-7"
|
|
107
|
+
|
|
108
|
+
test "Float.parse and Float.toStr go through Decimal"
|
|
109
|
+
assert Float.parse("0.3")! == 0.3 && Float.parse("2.5e-3")! == 0.0025 && Float.parse("-7")! == -7.0
|
|
110
|
+
assert Float.parse("1e400")! > Float.Max && Float.parse("abc").isErr() && Float.parse("").isErr()
|
|
111
|
+
assert 1.0e20.toStr() == "100000000000000000000.0"
|
|
112
|
+
assert {-1.0e20}.toStr() == "-100000000000000000000.0"
|
|
113
|
+
assert 9223372036854775808.0.toStr() == "9223372036854775808.0"
|
|
114
|
+
assert 1.0e23.toStr() == "99999999999999991611392.0"
|
|
115
|
+
assert 1.0e300.toStr() == "1000000000000000052504760255204420248704468581108159154915854115511802457988908195786371375080447864043704443832883878176942523235360430575644792184786706982848387200926575803737830233794788090059368953234970799945081119038967640880074652742780142494579258788820056842838115669472196386865459400540160.0"
|
|
116
|
+
assert Float.Max.toStr() == "179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.0"
|
|
117
|
+
assert {-Float.Max}.toStr() == "-179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.0"
|
|
118
|
+
|
|
119
|
+
test "6000 random bit patterns (and their negatives) round-trip through ofFloat, toStr, parse and exact"
|
|
120
|
+
bad := 1.to(3000).fold(Pair(first: 88172645463325252, second: 0), |acc, i|
|
|
121
|
+
x0 := acc.first
|
|
122
|
+
x1 := x0 ^ {x0 << 13}
|
|
123
|
+
x2 := x1 ^ {x1 >> 7}
|
|
124
|
+
x3 := x2 ^ {x2 << 17}
|
|
125
|
+
Pair(first: x3, second: if roundTrips(x3) && roundTrips(x3 >> 12) then acc.second else acc.second + 1)
|
|
126
|
+
)
|
|
127
|
+
assert bad.second == 0
|
tests/std/decimal.plum
DELETED
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Float
|
|
3
|
-
import std/Str
|
|
4
|
-
import std/Option
|
|
5
|
-
import std/decimal
|
|
6
|
-
import std/Pair
|
|
7
|
-
|
|
8
|
-
fun roundTrips(bits: Int) -> Bool =
|
|
9
|
-
x := Float.fromBits(bits & 0x7FFF_FFFF_FFFF_FFFF)
|
|
10
|
-
if x != x || x > Float.Max
|
|
11
|
-
true
|
|
12
|
-
else
|
|
13
|
-
decimal.parse(decimal.format(x))! == x && decimal.parse(decimal.format(0.0 - x))! == 0.0 - x
|
|
14
|
-
|
|
15
|
-
test "decimal.parse: nearest Float, edges, bad text"
|
|
16
|
-
assert decimal.parse("0.3")! == 0.3
|
|
17
|
-
assert decimal.parse("123.456")! == 123.456
|
|
18
|
-
assert decimal.parse("0.1234567890123")! == 0.1234567890123
|
|
19
|
-
assert decimal.parse("1e400")! > Float.Max
|
|
20
|
-
assert decimal.parse("1e-400")! == 0.0
|
|
21
|
-
assert decimal.parse("2.2250738585072014e-308")! == 2.2250738585072014e-308
|
|
22
|
-
assert decimal.parse("4.9406564584124654e-324")! == 4.9406564584124654e-324
|
|
23
|
-
assert decimal.parse("9007199254740993")! == 9007199254740992.0
|
|
24
|
-
assert decimal.parse("9007199254740995")! == 9007199254740996.0
|
|
25
|
-
assert decimal.parse("1.7976931348623157e308")! == Float.Max
|
|
26
|
-
assert decimal.parse("3.14159265358979")! == 3.14159265358979
|
|
27
|
-
assert decimal.parse("x").isNone()
|
|
28
|
-
assert decimal.parse("1e").isNone()
|
|
29
|
-
assert decimal.parse(".").isNone()
|
|
30
|
-
|
|
31
|
-
test "decimal.format: shortest digits, as JavaScript writes them"
|
|
32
|
-
assert decimal.format(0.1) == "0.1"
|
|
33
|
-
assert decimal.format(123.0) == "123"
|
|
34
|
-
assert decimal.format(0.1234567) == "0.1234567"
|
|
35
|
-
assert decimal.format(1e21) == "1e+21"
|
|
36
|
-
assert decimal.format(1e-7) == "1e-7"
|
|
37
|
-
assert decimal.format(Float.Max) == "1.7976931348623157e+308"
|
|
38
|
-
assert decimal.format(5e-324) == "5e-324"
|
|
39
|
-
assert decimal.format(0.1 + 0.2) == "0.30000000000000004"
|
|
40
|
-
assert decimal.format(-1.5) == "-1.5"
|
|
41
|
-
assert decimal.format(1e20) == "100000000000000000000"
|
|
42
|
-
assert decimal.format(123456.789) == "123456.789"
|
|
43
|
-
|
|
44
|
-
test "6000 random bit patterns (and their negatives) round-trip through format and parse"
|
|
45
|
-
bad := 1.to(3000).fold(Pair(first: 88172645463325252, second: 0), |acc, i|
|
|
46
|
-
x0 := acc.first
|
|
47
|
-
x1 := x0 ^ {x0 << 13}
|
|
48
|
-
x2 := x1 ^ {x1 >> 7}
|
|
49
|
-
x3 := x2 ^ {x2 << 17}
|
|
50
|
-
Pair(first: x3, second: if roundTrips(x3) && roundTrips(x3 >> 12) then acc.second else acc.second + 1)
|
|
51
|
-
)
|
|
52
|
-
assert bad.second == 0
|