Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Mar 1, 2016
Merged

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

merged 1 commit into from
Mar 1, 2016

Conversation

benjoffe
Copy link
Contributor

@benjoffe benjoffe commented Mar 1, 2016

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:

  • speed improvement for a large range of input values
  • slightly more accurate for a few values close to 20 (will be 1 instead of 0.999... as was previously being calculated).
  • smaller source

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
Copy link
Collaborator

ljharb commented Mar 1, 2016

👏 👏 Well documented, tested, and explained. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants