def test_pinv_solve(): # Fully determined system (unique result, identical to other solvers). A = Matrix([[1, 5], [7, 9]]) B = Matrix([12, 13]) assert A.pinv_solve(B) == A.cholesky_solve(B) assert A.pinv_solve(B) == A.LDLsolve(B) assert A.pinv_solve(B) == Matrix([sympify('-43/26'), sympify('71/26')]) assert A * A.pinv() * B == B # Fully determined, with two-dimensional B matrix. B = Matrix([[12, 13, 14], [15, 16, 17]]) assert A.pinv_solve(B) == A.cholesky_solve(B) assert A.pinv_solve(B) == A.LDLsolve(B) assert A.pinv_solve(B) == Matrix([[-33, -37, -41], [69, 75, 81]]) / 26 assert A * A.pinv() * B == B # Underdetermined system (infinite results). A = Matrix([[1, 0, 1], [0, 1, 1]]) B = Matrix([5, 7]) solution = A.pinv_solve(B) w = {} for s in solution.atoms(Symbol): # Extract dummy symbols used in the solution. w[s.name] = s assert solution == Matrix( [[w['w0_0'] / 3 + w['w1_0'] / 3 - w['w2_0'] / 3 + 1], [w['w0_0'] / 3 + w['w1_0'] / 3 - w['w2_0'] / 3 + 3], [-w['w0_0'] / 3 - w['w1_0'] / 3 + w['w2_0'] / 3 + 4]]) assert A * A.pinv() * B == B # Overdetermined system (least squares results). A = Matrix([[1, 0], [0, 0], [0, 1]]) B = Matrix([3, 2, 1]) assert A.pinv_solve(B) == Matrix([3, 1]) # Proof the solution is not exact. assert A * A.pinv() * B != B
def test_cholesky_solve(): A = Matrix([[2, 3, 5], [3, 6, 2], [8, 3, 6]]) x = Matrix(3, 1, [3, 7, 5]) b = A * x soln = A.cholesky_solve(b) assert soln == x A = Matrix([[0, -1, 2], [5, 10, 7], [8, 3, 4]]) x = Matrix(3, 1, [-1, 2, 5]) b = A * x soln = A.cholesky_solve(b) assert soln == x A = Matrix(((1, 5), (5, 1))) x = Matrix((4, -3)) b = A * x soln = A.cholesky_solve(b) assert soln == x A = Matrix(((9, 3 * I), (-3 * I, 5))) x = Matrix((-2, 1)) b = A * x soln = A.cholesky_solve(b) assert expand_mul(soln) == x A = Matrix(((9 * I, 3), (-3 + I, 5))) x = Matrix((2 + 3 * I, -1)) b = A * x soln = A.cholesky_solve(b) assert expand_mul(soln) == x a00, a01, a11, b0, b1 = symbols('a00, a01, a11, b0, b1') A = Matrix(((a00, a01), (a01, a11))) b = Matrix((b0, b1)) x = A.cholesky_solve(b) assert simplify(A * x) == b
def test_issue_17247_expression_blowup_30(): M = Matrix( S('''[ [ -3/4, 45/32 - 37*I/16, 0, 0], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128], [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0], [ 0, 0, 0, -177/128 - 1369*I/128]]''' )) assert M.cholesky_solve(ones(4, 1)) == Matrix( S('''[ [ -32549314808672/3306971225785 - 17397006745216*I/3306971225785], [ 67439348256/3306971225785 - 9167503335872*I/3306971225785], [-15091965363354518272/21217636514687010905 + 16890163109293858304*I/21217636514687010905], [ -11328/952745 + 87616*I/952745]]''' ))