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.
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.
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.