cosh function

double cosh(
  1. double x
)

Compute the hyperbolic cosine of a number.

Implementation

double cosh(double x) {
  if (x != x) {
    return x;
  }

  // cosh[z] = (exp(z) + exp(-z))/2

  // for numbers with magnitude 20 or so,
  // exp(-z) can be ignored in comparison with exp(z)

  if (x > 20) {
    if (x >= logMaxValue) {
      // Avoid overflow (MATH-905).
      final t = math.exp(0.5 * x);
      return (0.5 * t) * t;
    } else {
      return 0.5 * exp(x);
    }
  } else if (x < -20) {
    if (x <= -logMaxValue) {
      // Avoid overflow (MATH-905).
      final t = exp(-0.5 * x);
      return (0.5 * t) * t;
    } else {
      return 0.5 * exp(-x);
    }
  }

  //final hiPrec = List<double>(2);
  final hiPrec = List.filled(2, 0.0);
  if (x < 0.0) {
    x = -x;
  }
  exp(x, 0.0, hiPrec);

  var ya = hiPrec[0] + hiPrec[1];
  var yb = -(ya - hiPrec[0] - hiPrec[1]);

  var temp = ya * hex40000000;
  final yaa = ya + temp - temp;
  final yab = ya - yaa;

  // recip = 1/y
  final recip = 1.0 / ya;
  temp = recip * hex40000000;
  final recipa = recip + temp - temp;
  var recipb = recip - recipa;

  // Correct for rounding in division
  recipb +=
      (1.0 - yaa * recipa - yaa * recipb - yab * recipa - yab * recipb) * recip;
  // Account for yb
  recipb += -yb * recip * recip;

  // y = y + 1/y
  temp = ya + recipa;
  yb += -(temp - ya - recipa);
  ya = temp;
  temp = ya + recipb;
  yb += -(temp - ya - recipb);
  ya = temp;

  return (ya + yb) * 0.5;
}