python e**(-x)溢出错误:(34,“结果太大”)

时间:2022-06-24 18:20:18

Is there a way in python to truncate the decimal part at 5 or 7 digits?

在python中是否有一种方法将小数部分截断为5或7位数字?

If not, how can i avoid a float like e**(-x) number to get too big in size?

如果没有,如何避免像e**(-x)号那样的浮点数变得过大?

Thanks

谢谢

3 个解决方案

#1


5  

Either catch the OverflowError or use the decimal module. Python is not going to assume you were okay with the overflow.

要么捕获溢出错误,要么使用decimal模块。Python不会假设你对溢流很好。

>>> 0.0000000000000000000000000000000000000000000000000000000000000001**-30
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: (34, 'Result too large')
>>> d = decimal.Decimal(0.0000000000000000000000000000000000000000000000000000000000000001)
>>> d**-30
Decimal('1.000000000000001040827834994E+1920')

#2


2  

The "Result too large" doesn't refer to the number of characters in the decimal representation of the number, it means that the number that resulted from your exponential function is large enough to overflow whatever type python uses internally to store floating point values.

“结果太大”并不是指数字的十进制表示中的字符数,而是指由指数函数导致的数字大到足以溢出python内部用来存储浮点值的任何类型。

You need to either use a different type to handle your floating point calculations, or rework you code so that e**(-x) doesn't overflow or underflow.

您需要使用不同的类型来处理浮点计算,或者重新编写代码,使e**(-x)不会溢出或溢出。

#3


0  

this seems to work

这似乎工作

from decimal import *
getcontext().prec = 7
math.exp(- Decimal(x))

#1


5  

Either catch the OverflowError or use the decimal module. Python is not going to assume you were okay with the overflow.

要么捕获溢出错误,要么使用decimal模块。Python不会假设你对溢流很好。

>>> 0.0000000000000000000000000000000000000000000000000000000000000001**-30
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: (34, 'Result too large')
>>> d = decimal.Decimal(0.0000000000000000000000000000000000000000000000000000000000000001)
>>> d**-30
Decimal('1.000000000000001040827834994E+1920')

#2


2  

The "Result too large" doesn't refer to the number of characters in the decimal representation of the number, it means that the number that resulted from your exponential function is large enough to overflow whatever type python uses internally to store floating point values.

“结果太大”并不是指数字的十进制表示中的字符数,而是指由指数函数导致的数字大到足以溢出python内部用来存储浮点值的任何类型。

You need to either use a different type to handle your floating point calculations, or rework you code so that e**(-x) doesn't overflow or underflow.

您需要使用不同的类型来处理浮点计算,或者重新编写代码,使e**(-x)不会溢出或溢出。

#3


0  

this seems to work

这似乎工作

from decimal import *
getcontext().prec = 7
math.exp(- Decimal(x))