paulmillr / es6-shim

ECMAScript 6 compatibility shims for legacy JS engines
http://paulmillr.com
MIT License
3.11k stars 387 forks source link

Early exit from tanh for values >=20 <=-20 as JS loses precision #411

Closed benjoffe closed 8 years ago

benjoffe commented 8 years ago

tanh tends to Infinity very quickly. See the calculations of tanh at the boundary integers of 19 and 20 below. The value is calculated via wolfram alpha then pasted into a JS console to check if JS can represent the value.

tanh(19) https://www.wolframalpha.com/input/?i=tanh+19 result = 0.99999999999999993721734415903940939665164417761315093858 JS: 0.9999999999999999

tanh(20) https://www.wolframalpha.com/input/?i=tanh+20 result = 0.999999999999999991503291489416822045438558191190987257130 JS: 1

As can be seen, tanh(20) is equal to 1. Since tanh(Infinity) is also equal to 1 we can treat anything >= 20 as 1. tanh is an 'odd' function so the same applies to negative values.

Benefits of exiting early:

Note: there are values between 19 and 20 that also round to 1 but the source should be kept clean at an integer value.

ljharb commented 8 years ago

:clap: :clap: Well documented, tested, and explained. Thanks!