Backslash for solving linear systems¶
For a square matrix \(A\), the command A\b
is mathematically equivalent to \(A^{-1}b\). This command is not part of the core Julia, though, so it has to be explicitly loaded before the first use in a session.
using LinearAlgebra
A = [1 0 -1; 2 2 1; -1 -3 0]
3×3 Array{Int64,2}:
1 0 -1
2 2 1
-1 -3 0
b = [1,2,3]
3-element Array{Int64,1}:
1
2
3
x = A\b
3-element Array{Float64,1}:
2.1428571428571432
-1.7142857142857144
1.1428571428571428
One way to check the answer is to compute a quantity known as the residual. It is (hopefully) close to machine precision, scaled by the size of the entries of the data.
residual = b - A*x
3-element Array{Float64,1}:
-4.440892098500626e-16
-4.440892098500626e-16
0.0
If the matrix \(A\) is singular, you may get an error (“exception” in Julia-speak).
A = [0 1; 0 0];
b = [1,-1];
# x = A\b causes LAPACKException
It’s not exactly user-friendly here. Moreover, detecting singularity is a lot like checking whether two floating point numbers are exactly equal: because of roundoff, it could be missed. We’re headed toward a more robust way to fully describe the situation.