In [1]:
import numpy as np
In [2]:
#使用assert_almost_equal函数来检查它们是否近似相等
#指定精度,小数点后7位
print "Decimal 6", np.testing.assert_almost_equal(0.123456789, 0.123456780, decimal=7)
In [3]:
#指定精度,小数点后8位
#抛出异常
print "Decimal 7", np.testing.assert_almost_equal(0.123456789, 0.123456780, decimal=8)
In [4]:
# 指定8位有效数字
print "Significance 8", np.testing.assert_approx_equal(0.123456789,0.123456780, significant=8)
In [5]:
# 指定9位有效数字
# 抛出异常
print "Significance 9", np.testing.assert_approx_equal(0.123456789,0.123456780, significant=9)
In [6]:
print "Decimal 8", np.testing.assert_array_almost_equal([0, 0.123456789], [0, 0.123456780], decimal=8)
In [7]:
print "Decimal 9", np.testing.assert_array_almost_equal([0, 0.123456789], [0, 0.123456780], decimal=9)
比较数组也可以使用assert_allclose函数。该函数有参数atol(absolute tolerance,绝对容差限)和rtol(relative tolerance,相对容差限)。对于两个数组a和b,将测试是否满足以下条件:| a - b | <= (atol+rtol*b)
In [8]:
print "Pass", np.testing.assert_allclose([0,0.123456789,np.nan],[0,0.123456780,np.nan], rtol=1e-7,atol=0)
In [9]:
print "Fail", np.testing.assert_array_equal([0,0.123456789,np.nan],[0,0.123456780,np.nan])
In [10]:
# assert_array_less函数比较两个有严格顺序的数组
print "Pass", np.testing.assert_array_less([0,0.1,np.nan], [1,0.2,np.nan])
In [11]:
print "Fail", np.testing.assert_string_equal("NumPy", "Numpy")
In [12]:
# 使用finfo函数确定机器精度
eps = np.finfo(float).eps
print "Eps", eps
使用assert_array_almost_equal_nulp函数比较两个近似相等的浮点数1.0和1.0+eps
In [13]:
print "one eps", np.testing.assert_array_almost_equal_nulp(1.0, 1.0+eps)
In [14]:
print "two eps", np.testing.assert_array_almost_equal_nulp(1.0, 1.0+eps*2)
多ULP浮点数的比较
assert_array_max_ulp函数可以指定ULP的数量作为允许的误差上界。参数maxulp接受整数作为ULP数量的上限,默认值为1。
In [15]:
print "one eps", np.testing.assert_array_max_ulp(1.0, 1.0+eps)
In [17]:
print "two eps", np.testing.assert_array_max_ulp(1.0, 1.0+eps*2,maxulp=2)