math.log 函数中的 python 数学域错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19095774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:50:55  来源:igfitidea点击:

python math domain errors in math.log function

pythonmath

提问by Felix

I have to use Python math.log(x)function with values of xfrom (0, ..., 1). Sometimes x may be too close to zero, and Python gives me an error:

我必须使用 Pythonmath.log(x)函数和xfrom (0, ..., 1) 的值。有时 x 可能太接近于零,Python 给我一个错误:

ValueError: math domain error

ValueError:数学域错误

How can I know, what is the domain of definition of math.logfunction?

我怎么知道,math.log函数定义的域是什么?

采纳答案by Sven Marnach

As long as your input is within the half-open interval (0, 1] (not including 0), you are fine. You can't be too close to zero:

只要您的输入在半开区间 (0, 1] (不包括 0) 内,您就可以了。您不能太接近于零:

>>> math.log(sys.float_info.min)
-708.3964185322641

So simply checking for exactly zero (maybe as the result of an underflow) should be enough, or alternatively catch the exception and handle it.

所以简单地检查零(可能是下溢的结果)就足够了,或者捕获异常并处理它。

EDIT: This also holds for the denormal minimum floating point number:

编辑:这也适用于非正规最小浮点数:

>>> math.log(sys.float_info.min * sys.float_info.epsilon)
-744.4400719213812

回答by ismail

You are going over the supported precision, use Decimalclass instead.

您正在检查支持的精度,请改用Decimal类。

>>> from math import log
>>> from decimal import Decimal

>>> d = Decimal('1E-1024')
>>> log(d)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
>>> d.ln()
Decimal('-2357.847135225902780434423250')