Skip to content

Commit fb8300d

Browse files
committed
parse_number: divide by exact power of ten so short decimals match strtod
1 parent 7ab30db commit fb8300d

2 files changed

Lines changed: 39 additions & 1 deletion

File tree

‎smoke.c‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -913,6 +913,29 @@ void test_number() {
913913
lok(err != 0);
914914
}
915915
}
916+
917+
/* Short decimal literals (up to 15 significant digits) must match strtod
918+
* exactly, not just within the fuzz slack above. Scaling by an inexact
919+
* pow(10, -n) made these one ulp off, so 0.1+0.2==0.3 was true. */
920+
{
921+
const char *exact[] = {
922+
"0.3", "0.7", "867.4", "26.06", "522.526", "1.1", "2.675",
923+
"0.0001", "123456.789", "9.87654321e-5", "4.35e-10", "1.5e-22",
924+
"0.1", "0.2", "3.14159265358979"
925+
};
926+
int j;
927+
for (j = 0; j < (int)(sizeof(exact) / sizeof(*exact)); ++j) {
928+
int err;
929+
const double expected = strtod(exact[j], 0);
930+
const double got = te_interp(exact[j], &err);
931+
lok(err == 0 && got == expected);
932+
if (err != 0 || got != expected)
933+
printf("FAILED: %s => %.17g, expected %.17g (err=%d)\n",
934+
exact[j], got, expected, err);
935+
}
936+
lok(te_interp("0.1+0.2==0.3", 0) == 0.0);
937+
lok(te_interp("0.1+0.2", 0) == 0.1 + 0.2);
938+
}
916939
}
917940

918941

‎tinyexpr.c‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,15 @@ static double negate_logical_not(double a) {return -(a == 0.0);}
268268
static double negate_logical_notnot(double a) {return -(a != 0.0);}
269269

270270

271+
/* Powers of ten up to 1e22 are exactly representable as doubles. Dividing
272+
by one of these gives a correctly rounded result for literals with up to
273+
15 significant digits, whereas multiplying by an inexact pow(10, -n) can
274+
be off by one ulp (e.g. 0.3 would come out as 3 * 0.1). */
275+
static const double exact_pow10[] = {
276+
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11,
277+
1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22
278+
};
279+
271280
static double parse_number(state *s) {
272281
/* Parses a decimal or hex constant manually, so that the result does
273282
not depend on LC_NUMERIC. Sets s->type. */
@@ -331,7 +340,13 @@ static double parse_number(state *s) {
331340
}
332341

333342
/* The zero check keeps a huge exponent from producing 0 * inf. */
334-
if (exponent && value != 0.0) value *= pow(10.0, exponent);
343+
if (exponent && value != 0.0) {
344+
if (exponent < 0 && exponent >= -22) {
345+
value /= exact_pow10[-exponent];
346+
} else {
347+
value *= pow(10.0, exponent);
348+
}
349+
}
335350
}
336351

337352
s->type = TOK_NUMBER;

0 commit comments

Comments
 (0)