From c16bdb576b8c3e1f08faf7dce0118654d2c56bfb Mon Sep 17 00:00:00 2001 From: "Jan (janneke) Nieuwenhuizen" Date: Tue, 29 Dec 2020 22:39:31 +0100 Subject: [PATCH] core: Avoid Floating point exception dividing negative numbers. This fixes kaem --verbose --strict bin/mes-m2 -c '(display (/ -1 1))' * src/math.c (divide): Use signed division. --- src/math.c | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/math.c b/src/math.c index ba188422..75593cf1 100644 --- a/src/math.c +++ b/src/math.c @@ -156,18 +156,32 @@ divide (struct scm *x) /*:((name . "/") (arity . n)) */ n = v; x = cdr (x); } + int sign_p = 0; + size_t u = n; + if (n < 0) + { + sign_p = 1; + u = -n; + } + size_t w; while (x != cell_nil) { i = car (x); assert_number ("divide", i); v = i->value; + sign_p = sign_p && v > 0 || !sign_p && v < 0; + w = v; if (v == 0) error (cstring_to_symbol ("divide-by-zero"), x); - if (n == 0) + if (u == 0) break; - n = n / v; + if (w != 1) + u = u / w; x = cdr (x); } + n = u; + if (sign_p) + n = -n; return make_number (n); }