Skip to content

Commit

Permalink
improve safe_real
Browse files Browse the repository at this point in the history
  • Loading branch information
GiggleLiu committed May 13, 2024
1 parent 49c0342 commit e13af47
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 9 deletions.
9 changes: 4 additions & 5 deletions lib/YaoBlocks/src/utils.jl
Original file line number Diff line number Diff line change
Expand Up @@ -313,10 +313,9 @@ SparseArrays.sparse(et::EntryTable) = SparseVector(et)
Base.vec(et::EntryTable) = Vector(et)

# convert a (maybe complex) number x to real number.
function safe_real(x)
function safe_real(x::Complex{T}) where T
img = imag(x)
if !(iszero(img) || isapprox(x - im*img, x; atol=1e-15))
error("Can not convert number $x to real due to its large imaginary part.")
end
@assert iszero(img) || (hasmethod(eps, Tuple{Type{T}}) && isapprox(x - im*img, x; rtol=eps(T), atol=eps(T))) "Fail to convert number $x to real due to the nonzero imaginary part: $img."
return real(x)
end
end
safe_real(x) = x
4 changes: 0 additions & 4 deletions lib/YaoBlocks/test/blocktools.jl
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,4 @@ end
@test qc |> gatecount |> values |> sum == 6
res = gatecount(repeat(5, X, (2, 3)))
@test res |> values |> sum == 2
end

@testset "#issue 508" begin
@test YaoBlocks.safe_real(0 + 1e-323im) 0
end
9 changes: 9 additions & 0 deletions lib/YaoBlocks/test/utils.jl
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,13 @@ end
@test isclean(cet)
@test cet[bit"000"] == 1.0+0im
@test cet[bit"111"] == 0.0im
end

@testset "#issue 508" begin
@test YaoBlocks.safe_real(0 + 1e-323im) 0
@test YaoBlocks.safe_real(0+0im) 0
@test_throws AssertionError YaoBlocks.safe_real(0+1e-15im)
@test YaoBlocks.safe_real(0+1e-17im) == 0
@test YaoBlocks.safe_real(1e10+1e-10im) == 1e10
@test_throws AssertionError YaoBlocks.safe_real(0+1im)
end

0 comments on commit e13af47

Please sign in to comment.