python - Evaluate 1/tanh(x) - 1/x for very small x -
i need compute quantity
1/tanh(x) - 1/x
for x > 0
, x
can both small , large.
asymptotically small x
, have
1/tanh(x) - 1/x -> x / 3
and large x
1/tanh(x) - 1/x -> 1
anyhow, when computing expression, 10^-7
, smaller round-off errors lead expression being evaluated 0:
import numpy import matplotlib.pyplot plt x = numpy.array([2**k k in range(-30, 30)]) y = 1.0 / numpy.tanh(x) - 1.0 / x plt.loglog(x, y) plt.show()
use python package mpmath
arbitrary decimal precision. example:
import mpmath mpmath import mpf mpmath.mp.dps = 100 # set decimal precision x = mpf('1e-20') print (mpf('1') / mpmath.tanh(x)) - (mpf('1') / x) >>> 0.000000000000000000003333333333333333333333333333333333333333311111111111111111111946629156220629025294373160489201095913
it gets extremely precise.
look mpmath
plotting. mpmath
plays matplotlib
, using, should solve problem.
here example of how integrate mpmath code wrote above:
import numpy import matplotlib.pyplot plt import mpmath mpmath import mpf mpmath.mp.dps = 100 # set decimal precision x = numpy.array([mpf('2')**k k in range(-30, 30)]) y = mpf('1.0') / numpy.array([mpmath.tanh(e) e in x]) - mpf('1.0') / x plt.loglog(x, y) plt.show()
Comments
Post a Comment