Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate 1/tanh(x) - 1/x for very small x

I need to compute the quantity

1/tanh(x) - 1/x

for x > 0, where x can be both very small and very large.

Asymptotically for small x, we have

1/tanh(x) - 1/x  ->  x / 3

and for large x

1/tanh(x) - 1/x  ->  1

Anyhow, when computing the expression, already from 10^-7 and smaller round-off errors lead to the expression being evaluated as exactly 0:

import numpy
import matplotlib.pyplot as plt


x = numpy.array([2**k for k in range(-30, 30)])
y = 1.0 / numpy.tanh(x) - 1.0 / x

plt.loglog(x, y)
plt.show()

enter image description here

like image 255
Nico Schlömer Avatar asked Feb 05 '23 17:02

Nico Schlömer


1 Answers

For very small x, one could use the Taylor expansion of 1/tanh(x) - 1/x around 0,

y = x/3.0 - x**3 / 45.0 + 2.0/945.0 * x**5

The error is of the order O(x**7), so if 10^-5 is chosen as the breaking point, relative and absolute error will be well below machine precision.

import numpy
import matplotlib.pyplot as plt


x = numpy.array([2**k for k in range(-50, 30)])

y0 = 1.0 / numpy.tanh(x) - 1.0 / x
y1 = x/3.0 - x**3 / 45.0 + 2.0/945.0 * x**5
y = numpy.where(x > 1.0e-5, y0, y1)


plt.loglog(x, y)
plt.show()

enter image description here

like image 181
Nico Schlömer Avatar answered Feb 07 '23 17:02

Nico Schlömer