我正在尝试在 python 中计算 -1200 的指数(这是一个示例,我不需要特别需要 -1200,而是一组大约 -1200 的数字)。
>>> math.exp(-1200)
0.0
它给了我一个下溢;我该如何解决这个问题?
感谢您的帮助:)
最佳答案
在标准库中,可以查看decimal
模块:
>>> import decimal
>>> decimal.Decimal(-1200)
Decimal('-1200')
>>> decimal.Decimal(-1200).exp()
Decimal('7.024601888177132554529322758E-522')
如果您需要的函数比 decimal
支持的更多,您可以查看库 mpmath
,我经常使用并且非常喜欢它:
>>> import mpmath
>>> mpmath.exp(-1200)
mpf('7.0246018881771323e-522')
>>> mpmath.mp.dps = 200
>>> mpmath.exp(-1200)
mpf('7.0246018881771325545293227583680003334372949620241053728126200964731446389957280922886658181655138626308272350874157946618434229308939128146439669946631241632494494046687627223476088395986988628688095132e-522')
但如果可能,您应该看看是否可以重写您的方程式以完全在对数空间中工作。
关于python - python中非常小的指数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13115176/