Метод гаусса жордана питон

Метод Жордана-Гаусса в Python

Метод Жордана-Гаусса, также известный как метод Гаусса-Жордана, является численным методом решения системы линейных уравнений. Он основан на преобразовании расширенной матрицы системы к ступенчатому виду с помощью элементарных преобразований строк.

Алгоритм метода Жордана-Гаусса

  1. Выберите первое уравнение и разделите его на ведущий элемент (первый ненулевой элемент слева).
  2. Для всех остальных уравнений вычтите из них первое уравнение, умноженное на соответствующий множитель, чтобы их ведущий элемент стал равным нулю.
  3. Повторите шаги 1 и 2 для всех уравнений, кроме первого, используя каждый раз следующий элемент на главной диагонали в качестве ведущего элемента.
  4. Когда все уравнения станут приведенными, решение системы будет содержаться в последнем столбце расширенной матрицы.

Реализация на Python

def gauss_jordan(matrix): n = len(matrix) for i in range(n): pivot = matrix[i][i] for j in range(i, n + 1): matrix[i][j] /= pivot for k in range(n): if k != i: factor = matrix[k][i] for j in range(i, n + 1): matrix[k][j] -= factor * matrix[i][j] return [row[-1] for row in matrix] matrix = [ [2, -1, 5, 1, -3], [3, 2, 2, -6, -32], [1, 3, 3, -1, -47], [5, -2, -3, 3, 49], ] solution = gauss_jordan(matrix) print("Решение системы уравнений:", solution) 

Выше приведена реализация метода Жордана-Гаусса на языке Python. Данный код можно использовать для решения систем линейных уравнений с произвольным количеством переменных.

  • Получить ссылку
  • Facebook
  • Twitter
  • Pinterest
  • Электронная почта
  • Другие приложения
Читайте также:  JSON Test

Комментарии

Отправить комментарий

Популярные сообщения

Python вывести количество элементов списка

Python: Вывод количества элементов списка В этой статье мы рассмотрим как выводить количество элементов списка с помощью языка программирования Python. Использование функции len() Для определения количества элементов в списке в Python, используйте встроенную функцию len() . my_list = [1, 2, 3, 4, 5] elements_count = len(my_list) print(«Количество элементов в списке:», elements_count) Этот код создает список my_list , а затем использует функцию len() для подсчета элементов в списке. Результат будет выведен на экран. Использование цикла for Если вы хотите подсчитать количество элементов списка без использования функции len() , вы можете использовать цикл for . my_list = [1, 2, 3, 4, 5] elements_count = 0 for _ in my_list: elements_count += 1 print(«Количество элементов в списке:», elements_count) В этом примере мы инициализируем переменную elements_count значением 0, а затем для каждого элемента в списке увел

Python как перевести число в другую систему счисления

Преобразуйте числа как профессионал! Узнайте, как Python может перевести любое число в любую систему счисления. Даже если вы никогда раньше не сталкивались с программированием, эта статья поможет вам стать экспертом в считывании двоичных, восьмеричных и шестнадцатеричных чисел. Не пропустите возможность раскрыть секреты произвольной системы счисления в Python! Python: Перевод числа в другую систему счисления В языке программирования Python преобразование числа в другую систему счисления может быть выполнено с использованием встроенных функций и методов. Преобразование чисел в двоичную систему Python предоставляет встроенную функцию bin() для преобразования числа в двоичную систему. # Пример преобразования числа в двоичную систему num = 18 binary_num = bin(num) print(binary_num) # Вывод: 0b10010 Преобразование чисел в восьмеричную систему Функция oct() в Python преобразует число в восьмеричную систему. # Пример преобразования числа в восьмеричную систему num = 18

Читайте также:  Виды делений в python

Как сделать шашки на python

Как сделать шашки на Python Как сделать шашки на Python В этой статье мы рассмотрим, как создать простую игру в шашки на Python с использованием библиотеки Pygame. Подготовка Для начала установите библиотеку Pygame, используя следующую команду: pip install pygame Создание доски import pygame pygame.init() WIDTH, HEIGHT = 800, 800 ROWS, COLS = 8, 8 SQUARE_SIZE = WIDTH // COLS WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) BLUE = (0, 0, 255) def draw_board(win): win.fill(WHITE) for row in range(ROWS): for col in range(row % 2, COLS, 2): pygame.draw.rect(win, BLACK, (row * SQUARE_SIZE, col * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE)) def main(): win = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption(«Checkers») clock = pygame.time.Clock() run = True while run: clock.tick(60) for event in pygame.event.get(): if event.ty

Источник

Pure Python: Gauss-Jordan Solve Ax = b / invert A

ricardian ambivalence

Partly because I don’t know how to relax, I was doing some maths on a recent holiday.

My better half had persuaded me to leave my laptop at home, so I only had my iPad. This made doing real work difficult. Luckily(?), I have a python install on my iPad, so I was able to satisfy my curiosity.

I did, however, hit a wall when it came to regression as I was unable to invert matrices in the limited ‘pure python’ install I had available.

This little problem has been solved a million times already, but i’ve solved it again. The code is below in case anyone faces the same limitations.

The function implements the Gauss-Jordan algorithm for solving Ab = x, or inverting A, in pure python.

It works just like the solve() function in R.

If you call gj_Solve(A) — i.e. on a matrix A alone – the function will return A^-1. If you call gj_Solve(A, b), it returns [A|x], with A in reduced row echelon form.

It was an interesting little task. One fascinating issue i bumped into was the problem of numerical stability. See don’t invert that Matrix for an example.

# some helpers def idMatx(size): for i in range(size): id.append([0]*size) for i in range(size): id[i][i] = 1 return(id) def tranMtx(inMtx): tMtx = [] for row in range(0, len(inMtx[0])): tRow = [] for col in range(0, len(inMtx)): ele = inMtx[col][row] tRow.append(ele) tMtx.append(tRow) return(tMtx) def matxRound(matx, decPts=4): for col in range(len(matx)): for row in range(len(matx[0])): matx[col][row] = round(matx[col][row], decPts) # the solver . def gj_Solve(A, b=False, decPts=4): """ A gauss-jordan method to solve an augmented matrix for the unknown variables, x, in Ax = b. The degree of rounding is 'tuned' by altering decPts = 4. In the case where b is not supplied, b = ID matrix, and therefore the output is the inverse of the A matrix. """ if not b == False: # first, a test to make sure that A and b are conformable if (len(A) != len(b)): print 'A and b are not conformable' return Ab = A[:] Ab.append(b) m = tranMtx(Ab) else: ii = idMatx(len(A)) Aa = A[:] for col in range(len(ii)): Aa.append(ii[col]) tAa = tranMtx(Aa) m = tAa[:] (eqns, colrange, augCol) = (len(A), len(A), len(m[0])) # permute the matrix -- get the largest leaders onto the diagonals # take the first row, assume that x[1,1] is largest, and swap if that's not true for col in range(0, colrange): bigrow = col for row in range(col+1, colrange): if abs(m[row][col]) > abs(m[bigrow][col]): bigrow = row (m[col], m[bigrow]) = (m[bigrow], m[col]) print 'm is ', m # reduce, such that the last row is has at most one unknown for rrcol in range(0, colrange): for rr in range(rrcol+1, eqns): cc = -(float(m[rr][rrcol])/float(m[rrcol][rrcol])) for j in range(augCol): m[rr][j] = m[rr][j] + cc*m[rrcol][j] # final reduction -- the first test catches under-determined systems # these are characterised by some equations being all zero for rb in reversed(range(eqns)): if ( m[rb][rb] == 0): if m[rb][augCol-1] == 0: continue else: print 'system is inconsistent' return else: # you must loop back across to catch under-determined systems for backCol in reversed(range(rb, augCol)): m[rb][backCol] = float(m[rb][backCol]) / float(m[rb][rb]) # knock-up (cancel the above to eliminate the knowns) # again, we must loop to catch under-determined systems if not (rb == 0): for kup in reversed(range(rb)): for kleft in reversed(range(rb, augCol)): kk = -float(m[kup][rb]) / float(m[rb][rb]) m[kup][kleft] += kk*float(m[rb][kleft]) matxRound(m, decPts) if not b == False: return m else: mOut = [] for row in range(len(m)): rOut = [] for col in range(augCol/2, augCol): rOut.append(m[row][col]) mOut.append(rOut) return mOut # test it! A = [[1,2,4], [1,3,0], [1,5,5]] b = [5,8,2] sol = gj_Solve(A, b) print 'sol is ', sol inv = gj_Solve(A) print 'inv is ', inv

For those that wish to nerd-out on the iPad, I recommend Textastic for writing the code (it is light, while still being useful, and has good syntax highlighting), Python 2.7 for iOS for testing it, and a Logitech bluetooth keyboard case for your fingers.

Источник

Gauss–Jordan elimination over any field

While it’s typical to solve a system of linear equations in real numbers, it’s also possible to solve a linear system over any mathematical field. Here is Java and Python code that defines various fields and provides a version of Gauss–Jordan elimination that works on any field. The basic Gauss–Jordan elimination algorithm can be adapted to solve systems of linear equations, invert matrices, calculate determinants, calculate ranks, and more.

Source code

Java version

  • Field.java : Defines the constants and operations that every field must support.
  • Matrix.java : Represents a matrix and implements a collection of operations:
    • Basic information: Dimensions, get/set cell, clone, transpose
    • Row operations: Swap rows, multiply row, add two rows, multiply two matrices
    • Advanced operations: Gauss–Jordan elimination, determinant, inverse
    • DemoMain.java : A short demonstration program, which implements the “Rational numbers” example below.
    • MatrixTest.java : A JUnit test suite for Matrix .reducedRowEchelonForm() , Matrix .determinantAndRef() , and Matrix .invert() – mostly using PrimeField(11) .
    • PrimeField.java : Integers modulo a prime \(p\), also known as \(\mathbb_p\)
    • BinaryField.java : Polynomial coefficients over \(\mathbb_2\) modulo an irreducible polynomial, also known as \(\text(2^n)\)
    • RationalField.java , Fraction.java : Rational numbers (fractions), also known as \(\mathbb\)
    • QuadraticSurdField.java , QuadraticSurd.java : Irrational fractions of the form \(\frac>\), where \(a\), \(b\), \(c\), \(d\) are all integers; the special case of Gaussian rationals occurs when \(d = -1\)

    Python version

    • fieldmath.py: The library, including the classes Field , RationalField , PrimeField , BinaryField , QuadraticSurdField , QuadraticSurd , Matrix .
    • demo-main.py: A short demonstration program, which implements the “Rational numbers” example below.
    • matrix-test.py: A runnable test suite for fieldmath.Matrix.reduced_row_echelon_form() , fieldmath.Matrix.determinant_and_ref() , and fieldmath.Matrix.invert() – mostly using fieldmath.PrimeField(11) .

    Examples

    Suppose we want to solve this system of linear equations in rational numbers:

    \(\begin 2x + 5y + 3z &=& 7 \\ x + z &=& 1 \\ -4x + 2y — 9z &=& 6 \end \)

    First we convert the system into an augmented matrix:

    \(\begin 2 & 5 & 3 & 7 \\ 1 & 0 & 1 & 1 \\ -4 & 2 & -9 & 6 \end\)

    Then we perform Gauss–Jordan elimination on the matrix:

    \(\begin 1 & 0 & 0 & 67/27 \\ 0 & 1 & 0 & 35/27 \\ 0 & 0 & 1 & -40/27 \end\)

    And as long as the left side is the identity matrix, we can read the answer off the rightmost column:

    \(\begin x &=& 67/27 \\ y &=& 35/27 \\ z &=& -40/27 \end \)

    Here is the code to perform this example:

    // Nice-looking matrix int[][] input = < , , , >; // The actual matrix object Matrix mat = new Matrix( input.length, input[0].length, RationalField.FIELD); for (int i = 0; i < mat.rowCount(); i++) < for (int j = 0; j < mat.columnCount(); j++) mat.set(i, j, new Fraction(input[i][j], 1)); >// Gauss-Jordan elimination mat.reducedRowEchelonForm();

    Suppose we want to solve this system of linear equations modulo 7:

    \(\begin 3x + 1y + 4z &≡& 1 \mod 7 \\ 5x + 2y + 6z &≡& 5 \mod 7 \\ 0x + 5y + 2z &≡& 1 \mod 7 \end \)

    First we convert the system into an augmented matrix:

    \(\begin 3 & 1 & 4 & 1 \\ 5 & 2 & 6 & 5 \\ 0 & 5 & 2 & 1 \end\)

    Then we perform Gauss–Jordan elimination on the matrix:

    \(\begin 1 & 0 & 0 & 4 \\ 0 & 1 & 0 & 3 \\ 0 & 0 & 1 & 0 \end\)

    And as long as the left side is the identity matrix, we can read the answer off the rightmost column:

    \(\begin x &≡& 4 \mod 7 \\ y &≡& 3 \mod 7 \\ z &≡& 0 \mod 7 \end \)

    Here is the code to perform this example:

    // Nice-looking matrix int[][] input = < , , , >; // The actual matrix object Matrix mat = new Matrix( input.length, input[0].length, new PrimeField(7)); for (int i = 0; i < mat.rowCount(); i++) < for (int j = 0; j < mat.columnCount(); j++) mat.set(i, j, input[i][j]); >// Gauss-Jordan elimination mat.reducedRowEchelonForm();

    Browse Project Nayuki

    Feedback: Question/comment? Contact me

    Источник

Оцените статью