From: Eric Backus Subject: tanh() overflow To: djgpp AT sun DOT soe DOT clarkson DOT edu (djgpp) Date: Mon, 23 May 94 16:18:28 PDT Mailer: Elm [revision: 70.85] The definition of tanh() is: exp(x) - exp(-x) ---------------- exp(x) + exp(-x) The source code in /djgpp/libsrc/m/src/tanh.c implements this formula more-or-less directly, which is fine when the magnitude of x is small. However, when the magnitude of x is large, the calculation of exp(x) overflows. In this situation, the value returned by tanh(x) should be one, because in this situation, the exp(x) term is vastly bigger than the exp(-x) term. To fix this, we should do something like this: double tanh(double x) { if (x > 50) return 1; else if (x < -50) return -1; else { /* existing code goes here */ } } (I chose the value of 50 because tanh(50) is equal to one even if long doubles are used in the calculation, while exp(50) is small enough that it doesn't overflow even if floats are used in the calculation.) -- Eric Backus ericb AT lsid DOT hp DOT com (206) 335-2495