Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Overflow encountered with tanh function for large numbers #44

Open
richinex opened this issue Jun 13, 2023 · 0 comments
Open

Overflow encountered with tanh function for large numbers #44

richinex opened this issue Jun 13, 2023 · 0 comments

Comments

@richinex
Copy link

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);
    }
  }


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant