Complex.js icon indicating copy to clipboard operation
Complex.js copied to clipboard

Overflow encountered with tanh function for large numbers

Open richinex opened this issue 2 years ago • 0 comments

Hi, I work with impedance spectroscopy and I sometimes have to deal with large complex numbers. I experienced some overflow issues with the mathjs tanh implementation which I do not experience with Python. I raised the issue there and was asked to report it here since the tanh and coth functions for Complex numbers are currently straight from Complex.js library. See below example and kindly assist.

math.tanh(math.complex(1, 1))       // { re: 1.0839233273386948, im: 0.27175258531951174 }
math.tanh(math.complex(100, 100))   // { re: 1, im: -2.4171061928460553e-87 }
math.tanh(math.complex(1000, 1000)) // { re: NaN, im: -0 }

I thought I'd also share my custom implementation which is a translation of numba's implementation to JavaScript (although using mathjs)

import * as math from 'mathjs';

export function custom_tanh(z) {
    if (math.isComplex(z)) {
      const x = z.re;
      const y = z.im;

      if (Number.isFinite(x)) {
        const tx = math.tanh(x);
        const ty = Math.tan(y);
        const cx = 1 / math.cosh(x);
        const txty = tx * ty;

        const denom = 1 + txty * txty;
        const newRealPart = tx * (1 + ty * ty) / denom;
        const newImaginaryPart = ((ty / denom) * cx) * cx;

        return math.complex(newRealPart, newImaginaryPart);
      } else {
        const real = Math.sign(x);
        const imag = Number.isFinite(y) ? Math.sign(Math.sin(2 * y)) : 0;

        return math.complex(real, imag);
      }
    } else {
      return math.tanh(z);
    }
  }

 export function custom_coth(z) {
    if (math.isComplex(z)) {
      // Avoid division by zero
      if (z.re === 0 && z.im === 0) {
        return math.complex(Infinity, Infinity);
      }

      const tanhZ = custom_tanh(z);
      const one = math.complex(1, 0);
      return math.divide(one, tanhZ);
    } else {
      // Avoid division by zero
      if (z === 0) {
        return Infinity;
      }

      return 1 / math.tanh(z);
    }
  }


richinex avatar Jun 13 '23 08:06 richinex