unit utanh;

{$mode delphi}

interface

uses
  Classes, SysUtils, xmatdefs;

// result = ( exp( x ) - exp( -x ) ) / ( exp( x ) + exp( -x ) )
function tanh(x: NReal): Nreal;

// result =  1 - tanh( x )^2
function dev_tanh(x: NReal): NReal;


implementation
const
  C2 = (1-0.999999995877693);
  C1 = 0.999999995877693-C2/10.0;


function tanh(x: NReal): Nreal;
var
  a, b: NReal;
begin
  if x >= 10 then
    result:= C1+C2/x
  else if x <= -10 then
    result:= -C1+C2/x
  else
  begin
    a:= exp( x );
    b:= 1/a;
    result:= ( a - b ) /( a + b );
  end;
end;

function dev_tanh(x: NReal): NReal;
begin
  result:= 1 - sqr( tanh( x ) );
end;

end.
