Skip to content

Commit

Permalink
fix(math.sqrt): sqrt should raise ValueError when parameter is a nega…
Browse files Browse the repository at this point in the history
…tive number
  • Loading branch information
bofeng committed Oct 28, 2020
1 parent b763d3e commit aef2f89
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
7 changes: 5 additions & 2 deletions src/lib/math.js
Original file line number Diff line number Diff line change
Expand Up @@ -591,8 +591,11 @@ var $builtinmodule = function (name) {
mod.sqrt = new Sk.builtin.func(function sqrt(x) {
Sk.builtin.pyCheckArgsLen("sqrt", arguments.length, 1, 1);
Sk.builtin.pyCheckType("x", "number", Sk.builtin.checkNumber(x));

return new Sk.builtin.float_(Math.sqrt(Sk.builtin.asnum$(x)));
const _x = Sk.builtin.asnum$(x);
if (_x < 0) {
throw new Sk.builtin.ValueError("math domain error");
}
return new Sk.builtin.float_(Math.sqrt(_x));
});

// Trigonometric functions and Hyperbolic
Expand Down
4 changes: 2 additions & 2 deletions test/unit3/test_math.py
Original file line number Diff line number Diff line change
Expand Up @@ -1389,8 +1389,8 @@ def testSqrt(self):
self.ftest('sqrt(1)', math.sqrt(1), 1)
self.ftest('sqrt(4)', math.sqrt(4), 2)
self.assertEqual(math.sqrt(INF), INF)
# self.assertRaises(ValueError, math.sqrt, -1)
# self.assertRaises(ValueError, math.sqrt, NINF)
self.assertRaises(ValueError, math.sqrt, -1)
self.assertRaises(ValueError, math.sqrt, NINF)
self.assertTrue(math.isnan(math.sqrt(NAN)))

def testTan(self):
Expand Down

0 comments on commit aef2f89

Please sign in to comment.