Skip to content

Commit

Permalink
siground rounds to 0 when within 1e-15.
Browse files Browse the repository at this point in the history
`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.
  • Loading branch information
christianp committed Jan 16, 2024
1 parent e6ee6f3 commit c387528
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 0 deletions.
3 changes: 3 additions & 0 deletions runtime/scripts/math.js
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
},
Expand Down
3 changes: 3 additions & 0 deletions tests/jme-runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
},
Expand Down
2 changes: 2 additions & 0 deletions tests/jme/jme-tests.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
3 changes: 3 additions & 0 deletions tests/numbas-runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
},
Expand Down

0 comments on commit c387528

Please sign in to comment.