当然,使用isapprox 是一种相对简单的任意容差方法。例如:
julia> A = fill(-2.6e-9, 5,5)
5×5 Matrix{Float64}:
-2.6e-9 -2.6e-9 -2.6e-9 -2.6e-9 -2.6e-9
-2.6e-9 -2.6e-9 -2.6e-9 -2.6e-9 -2.6e-9
-2.6e-9 -2.6e-9 -2.6e-9 -2.6e-9 -2.6e-9
-2.6e-9 -2.6e-9 -2.6e-9 -2.6e-9 -2.6e-9
-2.6e-9 -2.6e-9 -2.6e-9 -2.6e-9 -2.6e-9
julia> map!(x -> isapprox(x, 0, atol=1e-8) ? 0 : x, A, A)
5×5 Matrix{Float64}:
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
请注意,使用map! 执行此操作不会分配,因此应该非常有效:
julia> @btime map!(x -> isapprox(x, 0, atol=1e-8) ? 0 : x, $A, $A)
30.984 ns (0 allocations: 0 bytes)
如果您没有指定容差(上面的 atol 选项所做的事情),它将使用一个有点复杂的公式为一般浮点工作选择一个合理的默认值:
isapprox(x, y; atol::Real=0, rtol::Real=atol>0 ? 0 : √eps, nans::Bool=false[, norm::Function])
Inexact equality comparison. Two numbers compare equal if their relative distance or
their absolute distance is within tolerance bounds: isapprox returns true if norm(x-y)
<= max(atol, rtol*max(norm(x), norm(y))). The default atol is zero and the default
rtol depends on the types of x and y. The keyword argument nans determines whether or
not NaN values are considered equal (defaults to false).
For real or complex floating-point values, if an atol > 0 is not specified, rtol
defaults to the square root of eps of the type of x or y, whichever is bigger (least
precise). This corresponds to requiring equality of about half of the significand
digits. Otherwise, e.g. for integer arguments or if an atol > 0 is supplied, rtol
defaults to zero.
关于您之前的计算中是否有任何问题:不一定,因为舍入误差是使用固定精度浮点数时不可避免的一部分。不过-2.6e-9 听起来确实有点大
julia> eps(0.0)
5.0e-324
所以这取决于你到底在做什么。例如,如果您要从彼此中减去两个大但相似的浮点数,那么对于 Float64s 而言,这种级别的错误可能并不令人惊讶