Skip to content

Commit

Permalink
Early exit from tanh for values >=20 <=-20 as JS loses precision for …
Browse files Browse the repository at this point in the history
…true value at this integer
  • Loading branch information
benjoffe committed Mar 1, 2016
1 parent d1ef165 commit 7b2414b
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
5 changes: 3 additions & 2 deletions es6-shim.js
Original file line number Diff line number Diff line change
Expand Up @@ -1957,8 +1957,9 @@
tanh: function tanh(value) {
var x = Number(value);
if (Number.isNaN(x) || x === 0) { return x; }
if (x === Infinity) { return 1; }
if (x === -Infinity) { return -1; }
// can exit early at +-20 as JS loses precision for true value at this integer
if (x >= 20) { return 1; }
if (x <= -20) { return -1; }
var a = Math.expm1(x);
var b = Math.expm1(-x);
if (a === Infinity) { return 1; }
Expand Down
5 changes: 4 additions & 1 deletion test/math.js
Original file line number Diff line number Diff line change
Expand Up @@ -605,7 +605,10 @@ describe('Math', function () {
expect(isNegativeZero(Math.tanh(-0))).to.equal(true);
expect(Math.tanh(Infinity)).to.equal(1);
expect(Math.tanh(-Infinity)).to.equal(-1);
expect(Math.tanh(90)).to.almostEqual(1);
expect(Math.tanh(19)).to.almostEqual(1);
expect(Math.tanh(-19)).to.almostEqual(-1);
expect(Math.tanh(20)).to.equal(1); // JS loses precision for true value at this integer
expect(Math.tanh(-20)).to.equal(-1); // JS loses precision for true value at this integer
expect(Math.tanh(10)).to.almostEqual(0.9999999958776927);
expect(Math.tanh(-2e-17)).to.equal(-2e-17);
});
Expand Down

2 comments on commit 7b2414b

@Yaffle
Copy link
Contributor

@Yaffle Yaffle commented on 7b2414b Mar 9, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ljharb the explicit edge case checks were removed in this commit, why didn't you worry?

@ljharb
Copy link
Collaborator

@ljharb ljharb commented on 7b2414b Mar 9, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The explicit edge case checks were just expanded from "infinity" to "gte 20" - as opposed to relying on obscure knowledge that another Math function covers them.

Please sign in to comment.