Skip to content

Instantly share code, notes, and snippets.

@KristofferC
Last active August 29, 2015 14:21
Show Gist options
  • Save KristofferC/27dd9e1577f779c0d177 to your computer and use it in GitHub Desktop.
Save KristofferC/27dd9e1577f779c0d177 to your computer and use it in GitHub Desktop.
function isnothermitian(A::SparseMatrixCSC)
m, n = size(A)
if m != n; return false; end
CHECK_PERCENTAGE = 0.001
colptr = A.colptr
rowval = A.rowval
nzval = A.nzval
nrnzval = length(nzval)
nrvals_check = trunc(Int, nrnzval * CHECK_PERCENTAGE)
c = 0
@inbounds for col = 1 : A.n, j = colptr[col] : colptr[col+1]-1
c += 1
if c > nrvals_check
break
end
row = rowval[j]
nz = nzval[j]
if nz != ctranspose(A[col, row])
return true
end
end
false
end
function ishermitian_fast(A::SparseMatrixCSC)
if isnothermitian(A)
return false
end
return countnz(A - A') == 0
end
function is_prob_hermitian{Tv, Ti}(A::SparseMatrixCSC{Tv, Ti}, tol = 10e-13)
if isnothermitian(A)
return false
end
# Heuristic check if <Ax, y> = <x, Ay>
# for random x and y
x = rand(Tv, A.n)
y = rand(Tv, A.n)
Axy = ((A*x)' * y)[1]
xAy = (x' * (A*y))[1]
res = abs(Axy - xAy) / sqrt(abs2(Axy) + abs2(xAy))
if res < tol
return true
end
return false
end
A = sprand(10^5,10^5, 0.001);
Aherm = A + A';
julia> @time ishermitian_fast(A)
# elapsed time: 1.8951e-5 seconds (160 bytes allocated)
# false
julia> @time ishermitian(A)
# elapsed time: 1.937657887 seconds (460 MB allocated, 4.44% gc time in 3 pauses with 1 full sweep)
# false
julia> @time is_prob_hermitian(A)
# elapsed time: 8.826e-6 seconds (160 bytes allocated)
# false
julia> @time ishermitian_fast(Aherm)
# elapsed time: 3.885827524 seconds (918 MB allocated, 2.94% gc time in 4 pauses with 2 full sweep)
# true
julia> @time ishermitian(Aherm)
# elapsed time: 4.004578854 seconds (918 MB allocated, 2.62% gc time in 4 pauses with 2 full sweep)
# true
julia> @time is_prob_hermitian(Aherm)
# elapsed time: 0.266606414 seconds (3 MB allocated)
# true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment