raz / commit 59f8ade1

commit
59f8ade1c313e758a20d3a7f8b89086cd244a214
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
8e8cefde
Fmt: short, a real in the fewest digits that read back

x, lo and hi, the halves to the F64s around it, are written out
exactly in decimal (base-10^9 big numbers, as arkusz's Afmt does), and
the two numbers of p digits nearest x are tried for p from 1 until one
lies between: no 17-digit rounding first, so the answer is always the
shortest and the nearest. With an exponent below 1E-4 and from 1E15 on;
-0.0 is -0. test/run/FmtShort checks round trips and that a digit fewer
fails, over powers of ten, hard values and 20,000 random bit patterns.

patch · log

4 files changed, +388 -2

doc/raz-lib.md (history) modified +8 -1

@@ -704,6 +704,7 @@
704704 char(c: U8);
705705 bool(b: BOOL);
706706 real(r: F64; places: INT);
707+ short(r: F64);
707708 end;
708709 proc print*(f: []U8; args: []Arg); (* to standard output *)
709710 proc eprint*(f: []U8; args: []Arg); (* to standard error, once Out is flushed *)
@@ -908,7 +909,13 @@
908909 default rounding, as Pascal's `Round`, where `round` is C's. `Fmt.real(x, places)` writes
909910 `x` with `places` digits after the point, at most 9, rounded to the
910911 nearest; from 1E15 on, with an exponent, as `1.50E17`; and `nan`,
911-`inf` and `-inf` as themselves. `hex` writes capitals and `lowHex`
912+`inf` and `-inf` as themselves. `Fmt.short(x)` writes `x` in the
913+fewest significant digits that `Math.toReal` reads back as the same
914+`F64`, and of two such the nearer `x`: `0.1`, not
915+`0.10000000000000001`; `42`, with no point; `0.0001`; and below 1E-4
916+or from 1E15 on with an exponent, as `1.5E17` or `5E-324`. Zero keeps
917+its sign, `0` or `-0`, and `nan` and `inf` are as `real` writes them.
918+`hex` writes capitals and `lowHex`
912919 lower case, neither with a `0x`. A width between the braces pads an
913920 argument to that many bytes: `{2}` with spaces on the left, `{02}`
914921 with zeros on the left, after a sign (`{04}` of -7 is `-007`), `{-10}`

lib/Fmt.raz (history) modified +277 -1

@@ -10,11 +10,28 @@
1010 module Fmt;
1111 import Out, Buf, Arena, Rt, Sys;
1212
13+const
14+ Limb = 1000000000; (* a Big's base, 10^9 *)
15+ LimbDigits = 9; (* the decimal digits of a limb *)
16+ LimbsMax = 90; (* limbs of the largest Big: 769 digits, for the least F64's lo *)
17+ MostDigits = 17; (* digits that always read back as the F64 they came from *)
18+ MantBits = 52; (* an F64's fraction bits *)
19+ ExpBias = 1075; (* its exponent's bias, with the fraction a whole number *)
20+ ExpMask = 7FFH; (* its exponent's bits, shifted down *)
21+ TwoStep = 29; (* doublings at once: 10^9 * 2^29 < 2^63 *)
22+ FiveStep = 13; (* fives multiplied at once: 10^9 * 5^13 < 2^63 *)
23+
1324 type
1425 (* An argument, and how it is printed. A real has places digits
1526 after the point, at most 9, rounded to the nearest, half away
1627 from zero; from 1E15 on, it has the exponent that makes it less
17- than 10, as 1.50E17; nan and inf are spelled so. *)
28+ than 10, as 1.50E17; nan and inf are spelled so. A short has the
29+ fewest significant digits that Math.toReal reads back as the
30+ same F64, the nearer of two such, and of two as near the one
31+ whose last digit is even; it is written as 0.0001, 0.1, 42 or
32+ 123456789012345, and with an exponent below 1E-4 and from 1E15
33+ on, as 1.5E17 or 5E-324. Zero is 0 or -0, keeping its sign so
34+ that it too reads back; nan and inf are spelled as real's. *)
1835 Arg* = variant
1936 int(i: I64); (* in decimal *)
2037 uint(u: U64); (* in decimal *)
@@ -24,6 +41,7 @@
2441 char(c: U8); (* the one byte *)
2542 bool(b: BOOL); (* true or false *)
2643 real(r: F64; places: INT);
44+ short(r: F64);
2745 end;
2846
2947 (* Where the pieces go: to out if slice is set, else to b, or to
@@ -43,8 +61,28 @@
4361 Spec = record
4462 width: INT;
4563 zero, left: BOOL;
64+ end;
65+
66+ (* A whole number, not negative, in base 10^9, the lowest limb
67+ first. *)
68+ Big = record
69+ v: [LimbsMax]U64;
70+ n: INT; (* the limbs in use *)
4671 end;
4772
73+ (* A number above 0, exactly in decimal: 0.d times 10^e, its first
74+ digit not 0. *)
75+ Exact = record
76+ d: [LimbsMax * LimbDigits]U8; (* '0' to '9' *)
77+ n, e: INT; (* how many digits, and the exponent *)
78+ end;
79+
80+ (* A number above 0 as short writes it, in the same way. *)
81+ Short = record
82+ d: [MostDigits]U8;
83+ n, e: INT;
84+ end;
85+
4886 (* The digits of u in base, at the end of the array: it and where they
4987 start. Digits past 9 are letters from letter on, 'A' or 'a'. *)
5088 proc digits(u: U64; base: U64; letter: U8): ([24]U8, INT);
@@ -127,8 +165,230 @@
127165 put(k, "E");
128166 put(k, d[at..24]);
129167 end;
168+end;
169+
170+(* ---- short: the fewest digits that read back ----
171+
172+ An F64 x is m times 2^k, m and k whole numbers. Every number between
173+ the halves to the F64s on either side of x reads back as x, so short
174+ looks for the fewest digits that land between those halves, lo and
175+ hi:
176+
177+ below lo x hi above the F64s around x
178+ |--------|------*------|--------|
179+
180+ x, lo and hi are written out exactly in decimal, each an Exact, and
181+ compared digit by digit with each try, so nothing is rounded on the
182+ way. For p digits the tries are x cut to p digits and that one more
183+ in its last place: the two numbers of p digits nearest x. The first
184+ p for which one of them lies between lo and hi gives the answer; if
185+ both do, the nearer x is taken. 17 digits are always enough.
186+
187+ An exact value is made in a Big, a whole number in base 10^9: for k
188+ at least 0, m times 2^k is m doubled k times; for k below 0, it is m
189+ times 5^-k with the point -k places from the right, since 2^-k is
190+ 5^-k / 10^-k. *)
191+
192+(* The bits of x. *)
193+proc bits(x: F64): U64;
194+var p: ^U64;
195+begin
196+ p := ^U64(ADR(x));
197+ return p^;
130198 end;
131199
200+(* b times f, which is at most 2^31. *)
201+proc bigMul(var b: Big; f: U64);
202+var i: INT; t, carry: U64;
203+begin
204+ carry := 0;
205+ for i := 0 to b.n - 1 do
206+ t := b.v[i] * f + carry;
207+ carry := t div Limb;
208+ b.v[i] := t - carry * Limb;
209+ end;
210+ while carry > 0 do
211+ b.v[b.n] := carry mod Limb;
212+ carry := carry div Limb;
213+ INC(b.n);
214+ end;
215+end;
216+
217+(* b times 2^k, or 5^k if five, a few steps at once. *)
218+proc bigPow(var b: Big; k: INT; five: BOOL);
219+var step, i: INT; f: U64;
220+begin
221+ while k > 0 do
222+ if five then step := FiveStep; else step := TwoStep; end;
223+ if k < step then step := k; end;
224+ f := 1;
225+ for i := 1 to step do
226+ if five then f := f * 5; else f := f * 2; end;
227+ end;
228+ bigMul(b, f);
229+ DEC(k, step);
230+ end;
231+end;
232+
233+(* m times 2^k, m not 0, exactly in decimal, into w. *)
234+proc expand(m: U64; k: INT; var w: Exact);
235+var b: Big; d: [24]U8; at, i, j, point: INT; v: U64;
236+begin
237+ b.n := 0;
238+ while m > 0 do
239+ b.v[b.n] := m mod Limb;
240+ m := m div Limb;
241+ INC(b.n);
242+ end;
243+ point := 0;
244+ if k < 0 then point := -k; bigPow(b, -k, true); else bigPow(b, k, false); end;
245+ (* the top limb without leading zeros, then nine digits a limb *)
246+ d, at := digits(b.v[b.n - 1], 10, 'A');
247+ w.n := 24 - at;
248+ COPY(w.d[0..w.n], d[at..24]);
249+ for i := b.n - 2 to 0 by -1 do
250+ v := b.v[i];
251+ for j := LimbDigits - 1 to 0 by -1 do
252+ w.d[w.n + j] := U8(v mod 10) + '0';
253+ v := v div 10;
254+ end;
255+ INC(w.n, LimbDigits);
256+ end;
257+ w.e := w.n - point;
258+end;
259+
260+(* -1, 0 or 1 as 0.d times 10^e, d's first digit not 0, is below, at or
261+ above w. *)
262+proc compare(d: []U8; e: INT; const w: Exact): INT;
263+var i, n: INT; a, c: U8;
264+begin
265+ if e # w.e then
266+ if e < w.e then return -1; end;
267+ return 1;
268+ end;
269+ n := w.n;
270+ if LEN(d) > n then n := LEN(d); end;
271+ for i := 0 to n - 1 do
272+ a := '0'; c := '0'; (* past its end each has zeros *)
273+ if i < LEN(d) then a := d[i]; end;
274+ if i < w.n then c := w.d[i]; end;
275+ if a # c then
276+ if a < c then return -1; end;
277+ return 1;
278+ end;
279+ end;
280+ return 0;
281+end;
282+
283+(* Whether s reads back as the F64 that lo and hi are the halves around:
284+ it lies between them, or on one of them if ends, as the F64 whose m
285+ is even takes a tie. *)
286+proc between(const s: Short; const lo, hi: Exact; ends: BOOL): BOOL;
287+var below, above: INT;
288+begin
289+ below := compare(s.d[0..s.n], s.e, lo);
290+ above := compare(s.d[0..s.n], s.e, hi);
291+ return ((below > 0) or (below = 0) and ends) and ((above < 0) or (above = 0) and ends);
292+end;
293+
294+(* s one more in its last place, carrying, without the zeros that leaves
295+ at the end: 129 becomes 13, and 99 becomes 1 with the point moved. *)
296+proc up(var s: Short);
297+var i: INT;
298+begin
299+ i := s.n - 1;
300+ while (i >= 0) and (s.d[i] = '9') do DEC(i); end;
301+ if i >= 0 then
302+ INC(s.d[i]);
303+ s.n := i + 1;
304+ else
305+ s.d[0] := '1';
306+ s.n := 1;
307+ INC(s.e);
308+ end;
309+end;
310+
311+(* Whether x, cut where rest begins, is nearer the number one more in
312+ the last place than to the cut one: rest is above a half, or a half
313+ and last, the cut one's last digit, odd. *)
314+proc nearerUp(rest: []U8; last: U8): BOOL;
315+var i: INT;
316+begin
317+ if rest[0] # '5' then return rest[0] > '5'; end;
318+ for i := 1 to LEN(rest) - 1 do
319+ if rest[i] # '0' then return true; end;
320+ end;
321+ return (last - '0') & 1 = 1;
322+end;
323+
324+(* The fewest digits that read back as x, finite and above 0, into s. *)
325+proc shortest(x: F64; var s: Short);
326+var u, m: U64; k, p: INT; mid, lo, hi: Exact; ends, downOk, upOk: BOOL; next: Short;
327+begin
328+ (* x as m times 2^k: the fraction with its hidden 1 but for the
329+ smallest exponent, the F64s below 2^-1022 *)
330+ u := bits(x);
331+ m := u & (U64(1) shl MantBits - 1);
332+ k := INT(u shr MantBits & ExpMask);
333+ if k = 0 then k := 1; else m := m | U64(1) shl MantBits; end;
334+ DEC(k, ExpBias);
335+ (* the halves to the F64s around x; the one below a power of two is
336+ half as far as the one above, but at the smallest exponent *)
337+ expand(m, k, mid);
338+ expand(2 * m + 1, k - 1, hi);
339+ if (m = U64(1) shl MantBits) and (k > 1 - ExpBias) then
340+ expand(4 * m - 1, k - 2, lo);
341+ else
342+ expand(2 * m - 1, k - 1, lo);
343+ end;
344+ ends := m & 1 = 0;
345+ for p := 1 to MostDigits do
346+ s.n := p;
347+ if p >= mid.n then s.n := mid.n; end; (* x itself has no more digits *)
348+ s.e := mid.e;
349+ COPY(s.d[0..s.n], mid.d[0..s.n]);
350+ if s.n = mid.n then return; end;
351+ next := s;
352+ up(next);
353+ downOk := between(s, lo, hi, ends);
354+ upOk := between(next, lo, hi, ends);
355+ if upOk and (not downOk or nearerUp(mid.d[p..mid.n], s.d[p - 1])) then
356+ s := next;
357+ return;
358+ elsif downOk then
359+ return;
360+ end;
361+ end;
362+end;
363+
364+(* x as Arg's short says, but for the minus sign, which arg writes. *)
365+proc putShort(var k: Sink; x: F64);
366+var s: Short; d: [24]U8; at, e: INT;
367+begin
368+ if x # x then put(k, "nan"); return; end;
369+ if x < 0.0 then x := -x; end;
370+ if x > 1.7976931348623157E308 then put(k, "inf"); return; end;
371+ if x = 0.0 then put(k, "0"); return; end; (* -0.0 too *)
372+ shortest(x, s);
373+ if (s.e >= -3) and (s.e <= 15) then (* from 1E-4 to below 1E15 *)
374+ if s.e <= 0 then
375+ put(k, "0."); fill(k, '0', -s.e); put(k, s.d[0..s.n]);
376+ elsif s.e >= s.n then
377+ put(k, s.d[0..s.n]); fill(k, '0', s.e - s.n);
378+ else
379+ put(k, s.d[0..s.e]); put(k, "."); put(k, s.d[s.e..s.n]);
380+ end;
381+ else
382+ put(k, s.d[0..1]);
383+ if s.n > 1 then put(k, "."); put(k, s.d[1..s.n]); end;
384+ put(k, "E");
385+ e := s.e - 1;
386+ if e < 0 then put(k, "-"); e := -e; end;
387+ d, at := digits(U64(e), 10, 'A');
388+ put(k, d[at..24]);
389+ end;
390+end;
391+
132392 (* Whether a is printed with a minus sign. *)
133393 proc negative(a: Arg): BOOL;
134394 var neg: BOOL;
@@ -136,6 +396,7 @@
136396 match a of
137397 | int(i): neg := i < 0;
138398 | real(r, _places): neg := r < 0.0;
399+ | short(r): neg := (r = r) and (bits(r) shr 63 = 1); (* -0.0 too, but no nan *)
139400 | else: neg := false;
140401 end;
141402 return neg;
@@ -160,6 +421,7 @@
160421 | char(c): one[0] := c; put(k, one);
161422 | bool(t): if t then put(k, "true"); else put(k, "false"); end;
162423 | real(r, places): putReal(k, r, places);
424+ | short(r): putShort(k, r);
163425 end;
164426 end;
165427
@@ -317,6 +579,20 @@
317579 Buf.reset(b);
318580 write(b, "{x} {2x} {0} {-} {a} {1", [int(1), int(2)]);
319581 if Buf.bytes(b) # "x 2x 1 - a 1" then Rt.stop("Fmt: a { that is no width"); end;
582+ Buf.reset(b);
583+ write(b, "{} {} {} {} {} {} {} {}", [short(0.1), short(1.0 / 3.0), short(-2.5), short(100.0), short(42.0E3),
584+ short(0.0001), short(0.00012), short(123456789012345.0)]);
585+ if Buf.bytes(b) # "0.1 0.3333333333333333 -2.5 100 42000 0.0001 0.00012 123456789012345" then Rt.stop("Fmt.short"); end;
586+ Buf.reset(b);
587+ write(b, "{} {} {} {} {} {} {}", [short(1.0E15), short(1.5E17), short(9.9E-5), short(5.0E-324),
588+ short(1.7976931348623157E308), short(2.2250738585072014E-308), short(9007199254740992.0)]);
589+ if Buf.bytes(b) # "1E15 1.5E17 9.9E-5 5E-324 1.7976931348623157E308 2.2250738585072014E-308 9.007199254740992E15" then
590+ Rt.stop("Fmt.short: an exponent");
591+ end;
592+ Buf.reset(b);
593+ write(b, "{} {} {} {} {} {6}|{-6}|{06}", [short(zero), short(-zero), short(1.0 / zero), short(-1.0 / zero),
594+ short(zero / zero), short(0.5), short(0.5), short(-0.5)]);
595+ if Buf.bytes(b) # "0 -0 inf -inf nan 0.5|0.5 |-000.5" then Rt.stop("Fmt.short: zero, inf, nan and a width"); end;
320596 n, whole := into(small, "{}:{02}", [int(-3), int(7)]);
321597 if (small[0..n] # "-3:07") or not whole then Rt.stop("Fmt.into"); end;
322598 n, whole := into(small, "line {}, {}", [int(12), str("x")]);

test/run/FmtShort.expect (history) added +1 -0

@@ -0,0 +1 @@
1+21266 values tried, 0 bad

test/run/FmtShort.raz (history) added +102 -0

@@ -0,0 +1,102 @@
1+(* Fmt.short against Math.toReal: what it writes reads back as the
2+ same F64, and one digit fewer does not. Tried on powers of ten, a
3+ few numbers known to be hard, and random bit patterns. *)
4+module FmtShort;
5+import Fmt, Math, Buf, Heap;
6+
7+var
8+ text, fewer: Buf.Buf;
9+ tried, bad: INT;
10+
11+(* What toReal reads s as; a nan if it reads nothing. *)
12+proc read(s: []U8): F64;
13+var x: F64; ok: BOOL;
14+begin
15+ x, ok := Math.toReal(s);
16+ if not ok then x := Math.fromBits(7FF8000000000000H); end;
17+ return x;
18+end;
19+
20+(* Whether y is x, -0.0 not being 0.0. *)
21+proc same(x, y: F64): BOOL;
22+begin
23+ return Math.bits(x) = Math.bits(y);
24+end;
25+
26+(* The significant digits of s, as short writes it, as a whole number,
27+ and the power of ten it is to be taken to: 1.5E17 is 15 and 16. *)
28+proc parse(s: []U8): (U64, INT);
29+var d: U64; e, i, ex: INT; point, neg: BOOL;
30+begin
31+ while (i < LEN(s)) and (s[i] # 'E') do
32+ if s[i] = '.' then
33+ point := true;
34+ elsif s[i] # '-' then
35+ d := d * 10 + U64(s[i] - '0');
36+ if point then DEC(e); end;
37+ end;
38+ INC(i);
39+ end;
40+ if i < LEN(s) then
41+ INC(i);
42+ if s[i] = '-' then neg := true; INC(i); end;
43+ while i < LEN(s) do ex := ex * 10 + INT(s[i] - '0'); INC(i); end;
44+ if neg then ex := -ex; end;
45+ end;
46+ while (d > 0) and (d mod 10 = 0) do d := d div 10; INC(e); end;
47+ return d, e + ex;
48+end;
49+
50+(* Whether d times 10^e reads back as x. *)
51+proc readsBack(d: U64; e: INT; x: F64): BOOL;
52+begin
53+ Buf.reset(fewer);
54+ Fmt.write(fewer, "{}E{}", [Fmt.uint(d), Fmt.int(e)]);
55+ return same(read(Buf.bytes(fewer)), x);
56+end;
57+
58+(* x, finite and not 0, tried. *)
59+proc check(x: F64);
60+var d: U64; e: INT;
61+begin
62+ INC(tried);
63+ Buf.reset(text);
64+ Fmt.write(text, "{}", [Fmt.short(x)]);
65+ if not same(read(Buf.bytes(text)), x) then
66+ INC(bad);
67+ Fmt.print("{} reads back as another F64\n", [Fmt.str(Buf.bytes(text))]);
68+ return;
69+ end;
70+ (* one digit fewer: the two numbers of that many digits around x *)
71+ if x < 0.0 then x := -x; end;
72+ d, e := parse(Buf.bytes(text));
73+ if (d >= 10) and (readsBack(d div 10, e + 1, x) or readsBack(d div 10 + 1, e + 1, x)) then
74+ INC(bad);
75+ Fmt.print("{} reads back in fewer digits\n", [Fmt.str(Buf.bytes(text))]);
76+ end;
77+end;
78+
79+proc main*;
80+var x: F64; u: U64; i: INT;
81+begin
82+ Buf.init(text, Heap.heap);
83+ Buf.init(fewer, Heap.heap);
84+ x := 1.0E-323;
85+ while x < 1.0E308 do check(x); check(-x); x := x * 10.0; end;
86+ x := 1.0;
87+ for i := 0 to 1073 do x := x / 2.0; end;
88+ check(x); (* the least F64, 5E-324 *)
89+ check(0.1); check(0.2); check(0.3); check(1.0 / 3.0); check(2.0 / 3.0);
90+ check(1.7976931348623157E308); check(2.2250738585072014E-308); check(2.2250738585072009E-308);
91+ check(9007199254740992.0); check(9007199254740993.0); check(5.0E-324); check(123456789.0);
92+ (* random bit patterns, nan and inf left out *)
93+ u := 12345;
94+ for i := 1 to 20000 do
95+ u := u * 6364136223846793005 + 1442695040888963407;
96+ x := Math.fromBits(u);
97+ if (x = x) and (x - x = 0.0) and (x # 0.0) then check(x); end;
98+ end;
99+ Fmt.print("{} values tried, {} bad\n", [Fmt.int(tried), Fmt.int(bad)]);
100+end;
101+
102+end FmtShort.