www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1994/05/23/19:47:30

From: Eric Backus <ericb AT lsid DOT hp DOT com>
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

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019