Skip to content

Commit ac0c1cd

Browse files
committed
Use SVD for computing the condition number of matrices (#1862)
Return Inf for singular matrices. cond(A,2) also returns NaN for all zeros input. To fix: cond(A,p) returns Inf for all zeros input except when p = 2.
1 parent 68e09fb commit ac0c1cd

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

base/linalg.jl

+13-2
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,19 @@ trace(A::AbstractMatrix) = sum(diag(A))
7272

7373
#det(a::AbstractMatrix)
7474
inv(a::AbstractMatrix) = a \ one(a)
75-
cond(a::AbstractMatrix, p) = norm(a, p) * norm(inv(a), p)
76-
cond(a::AbstractMatrix) = cond(a, 2)
75+
cond(a::AbstractMatrix) = (s = svdvals(a); max(s) / min(s))
76+
77+
function cond(a::AbstractMatrix, p)
78+
if p == 2
79+
return cond(a)
80+
else
81+
try
82+
return norm(a, p) * norm(inv(a), p)
83+
catch SingularException
84+
return Inf
85+
end
86+
end
87+
end
7788

7889
#issym(A::AbstractMatrix)
7990
#ishermitian(A::AbstractMatrix)

0 commit comments

Comments
 (0)