From c38752820cf44daee6037e9c57eb6d38d5f00d07 Mon Sep 17 00:00:00 2001 From: Christian Lawson-Perfect Date: Tue, 16 Jan 2024 09:39:38 +0000 Subject: [PATCH] siground rounds to 0 when within 1e-15. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `cos(pi/2)`, for example, is not exactly 0 due to floating point rounding error - it's 6.123233995736766e-17. This commit changes `math.siground` to round a to 0 when `isclose(a,0)`, which is true if it's ±1e-15. --- runtime/scripts/math.js | 3 +++ tests/jme-runtime.js | 3 +++ tests/jme/jme-tests.mjs | 2 ++ tests/numbas-runtime.js | 3 +++ 4 files changed, 11 insertions(+) diff --git a/runtime/scripts/math.js b/runtime/scripts/math.js index a0afa5aed..10a3c2c6a 100644 --- a/runtime/scripts/math.js +++ b/runtime/scripts/math.js @@ -1227,6 +1227,9 @@ var math = Numbas.math = /** @lends Numbas.math */ { if(a.complex) { return math.complex(math.siground(a.re,b),math.siground(a.im,b)); } else { + if(math.isclose(a,0)) { + return 0; + } return parseFloat(a.toPrecision(b)) } }, diff --git a/tests/jme-runtime.js b/tests/jme-runtime.js index 748122105..100314ef2 100644 --- a/tests/jme-runtime.js +++ b/tests/jme-runtime.js @@ -3448,6 +3448,9 @@ var math = Numbas.math = /** @lends Numbas.math */ { if(a.complex) { return math.complex(math.siground(a.re,b),math.siground(a.im,b)); } else { + if(math.isclose(a,0)) { + return 0; + } return parseFloat(a.toPrecision(b)) } }, diff --git a/tests/jme/jme-tests.mjs b/tests/jme/jme-tests.mjs index c9e130f29..08487c083 100644 --- a/tests/jme/jme-tests.mjs +++ b/tests/jme/jme-tests.mjs @@ -1011,6 +1011,8 @@ Numbas.queueScript('jme_tests',['qunit','jme','jme-rules','jme-display','jme-cal assert.equal(evaluate('ceil('+expr+')').value, c, 'ceil('+expr+')'); deepCloseEqual(assert,evaluate('fract('+expr+')'), evaluate(fr), 'fract('+expr+')'); }); + + assert.equal(evaluate('siground(cos(pi/2),3)').value, 0, 'siground(cos(pi/2))'); }); QUnit.test('Currency',function(assert) { diff --git a/tests/numbas-runtime.js b/tests/numbas-runtime.js index bcebc9684..da557f209 100644 --- a/tests/numbas-runtime.js +++ b/tests/numbas-runtime.js @@ -3449,6 +3449,9 @@ var math = Numbas.math = /** @lends Numbas.math */ { if(a.complex) { return math.complex(math.siground(a.re,b),math.siground(a.im,b)); } else { + if(math.isclose(a,0)) { + return 0; + } return parseFloat(a.toPrecision(b)) } },