def solve(a, b): """ Solve a linear matrix equation, or system of linear scalar equations using Gausian elimination. :param a: Coefficient matrix :type a: array_like, shape (M, M) :param b: Ordinate or "dependent variable" values :type b: array_like, shape (M,) or (M, N) :return: Solution to the system a x = b :rtype: ndarray, shape (M,) or (M, N) depending on b :raises: :py:exc:`LinAlgError` If `a` is singular or not square. **Examples:** Solve the system of equations ``3 * x0 + x1 = 9`` and ``x0 + 2 * x1 = 8``: >>> import bohrium as np >>> a = np.array([[3.,1.], [1.,2.]]) >>> b = np.array([9.,8.]) >>> x = np.linalg.solve(a, b) >>> x array([ 2., 3.]) Check that the solution is correct: >>> (np.dot(a, x) == b).all() True """ if not (len(a.shape) == 2 and a.shape[0] == a.shape[1]): raise la.LinAlgError("a is not square") w = gauss(np.hstack((a, b[:, np.newaxis]))) lc = w.shape[1] - 1 x = w[:, lc].copy() def loop_body(lc, x, w): c = get_iterator(1) x[:c] -= w[:c, c] * x[c:c + 1] # for c in range(lc - 1, 0, -1): # x[:c] -= w[:c, c] * x[c:c + 1] # np.flush() return x
def solve(a, b): """ Solve a linear matrix equation, or system of linear scalar equations using Gausian elimination. :param a: Coefficient matrix :type a: array_like, shape (M, M) :param b: Ordinate or "dependent variable" values :type b: array_like, shape (M,) or (M, N) :return: Solution to the system a x = b :rtype: ndarray, shape (M,) or (M, N) depending on b :raises: :py:exc:`LinAlgError` If `a` is singular or not square. **Examples:** Solve the system of equations ``3 * x0 + x1 = 9`` and ``x0 + 2 * x1 = 8``: >>> import bohrium as np >>> a = np.array([[3.,1.], [1.,2.]]) >>> b = np.array([9.,8.]) >>> x = np.linalg.solve(a, b) >>> x array([ 2., 3.]) Check that the solution is correct: >>> (np.dot(a, x) == b).all() True """ if not (len(a.shape) == 2 and a.shape[0] == a.shape[1]): raise la.LinAlgError("a is not square") w = gauss(np.hstack((a,b[:,np.newaxis]))) lc = w.shape[1]-1 x = w[:,lc].copy() for c in xrange(lc-1,0,-1): x[:c] -= w[:c,c] * x[c:c+1] np.flush(x) return x