python math.log函数中的数学域错误 [英] python math domain errors in math.log function
问题描述
我必须使用Python math.log(x)
函数,其值从(0,...,1)为 x .有时x可能太接近零,而Python给我一个错误:
I have to use Python math.log(x)
function with values of x from (0, ..., 1). Sometimes x may be too close to zero, and Python gives me an error:
ValueError:数学域错误
ValueError: math domain error
我怎么知道 math.log
函数的定义范围是什么?
How can I know, what is the domain of definition of math.log
function?
推荐答案
只要您的输入在半开间隔(0,1](不包括0)之内,就可以了.接近零:
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:
>>> 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
这篇关于python math.log函数中的数学域错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!