python numpy机器epsilon

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19141432/
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:59:03  来源:igfitidea点击:

python numpy machine epsilon

pythonnumpyepsilon

提问by Bob

I am trying to understand what is machine epsilon. According to the Wikipedia, it can be calculated as follows:

我试图了解什么是机器 epsilon。根据维基百科,它可以计算如下:

def machineEpsilon(func=float):
    machine_epsilon = func(1)
    while func(1)+func(machine_epsilon) != func(1):
        machine_epsilon_last = machine_epsilon
        machine_epsilon = func(machine_epsilon) / func(2)
    return machine_epsilon_last

However, it is suitable only for double precision numbers. I am interested in modifying it to support also single precision numbers. I read that numpy can be used, particularly numpy.float32class. Can anybody help with modifying the function?

但是,它仅适用于双精度数。我有兴趣修改它以支持单精度数字。我读到可以使用 numpy,尤其是numpy.float32class。有人可以帮忙修改函数吗?

采纳答案by ali_m

An easier way to get the machine epsilon for a given float type is to use np.finfo():

获取给定浮点类型的机器 epsilon 的更简单方法是使用np.finfo()

print(np.finfo(float).eps)
# 2.22044604925e-16

print(np.finfo(np.float32).eps)
# 1.19209e-07

回答by Claudiu

It will already work, as David pointed out!

正如大卫指出的那样,它已经可以工作了!

>>> def machineEpsilon(func=float):
...     machine_epsilon = func(1)
...     while func(1)+func(machine_epsilon) != func(1):
...         machine_epsilon_last = machine_epsilon
...         machine_epsilon = func(machine_epsilon) / func(2)
...     return machine_epsilon_last
... 
>>> machineEpsilon(float)
2.220446049250313e-16
>>> import numpy
>>> machineEpsilon(numpy.float64)
2.2204460492503131e-16
>>> machineEpsilon(numpy.float32)
1.1920929e-07

回答by Ullen

Another easy way to get epsilon is:

获得 epsilon 的另一种简单方法是:

In [1]: 7./3 - 4./3 -1
Out[1]: 2.220446049250313e-16