Skip to content

Implement gaussian elimination in python #370

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 23, 2018
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions contents/gaussian_elimination/code/python/gaussian_elimination.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import numpy as np

def gaussian_elimination(A):

pivot_row = 0

# Step 1: Go by column
for pivot_col in range(min(A.shape[0], A.shape[1])):

# Step 2: Swap row with highest element in col
max_i = np.argmax(abs(A[pivot_row:,pivot_col])) + pivot_row

temp = A[pivot_row,:].copy()
A[pivot_row,:] = A[max_i,:]
A[max_i,:] = temp

# Skip on singular matrix, not actually a pivot
if A[pivot_row, pivot_col] == 0:
continue

# Steps 3 & 4: Zero out elements below pivot
for r in range(pivot_row+1, A.shape[0]):
# Step 3: Get fraction
frac = -A[r,pivot_col] / A[pivot_row,pivot_col]
# Step 4: Add rows
A[r,:] = A[r,:] + frac*A[pivot_row,:]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use += here.


pivot_row += 1


"""
Assumes A is already ref
"""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you want a code comment and not an actual function docstring (which would go under the def), use the usual # syntax. Better to say "row echelon form" than "ref".

def gauss_jordon_elimination(A):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

jordon -> jordan


col = 0

# Scan for pivots
for row in range(A.shape[0]):
while col < A.shape[1] and A[row,col] == 0:
col += 1

if col >= A.shape[1]:
continue

# Set each pivot to one via row scaling
A[row,:] = A[row,:] / A[row,col]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use /= here.


# Zero out elements above pivot
for r in range(row):
A[r,:] = A[r,:] - A[r,col] * A[row,:]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use -= here.



"""
Assumes A has a unique solution and A in ref
"""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same docstring and ref comment.

def back_substitution(A):

sol = np.zeros(A.shape[0]).T

# Go by pivots along diagonal
for pivot_i in range(A.shape[0]-1, -1, -1):
s = 0
for col in range(pivot_i+1, A.shape[1]-1):
s += A[pivot_i,col] * sol[col]
sol[pivot_i] = (A[pivot_i,A.shape[1]-1] - s) / A[pivot_i,pivot_i]

return sol


def main():
A = np.matrix('2. 3 4 6; 1 2 3 4; 3 -4 0 10')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Generally, you want array and not matrix.
  2. The explicit form of initialization, rather than a string, is clearer.
  3. The single float to force the type is too easy to overlook. Either do
A = np.array([[2,  3, 4,  6],
              [1,  2, 3,  4],
              [3, -4, 0, 10]], dtype=float)

or

A = np.array([[2.0,  3.0, 4.0,  6.0],
              [1.0,  2.0, 3.0,  4.0],
              [3.0, -4.0, 0.0, 10.0]])


print("Original")
print(A, "\n")

gaussian_elimination(A)
print("Gaussian elimination, REF")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would not abbreviate REF in print output.

print(A, "\n")

print("Back subsitution")
print(back_substitution(A))
print()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you make this more consistent with the other printing sections?

print("Back substitution")
print(back_substitution(A), "\n")


gauss_jordon_elimination(A)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

jordon -> jordan

print("Gauss-Jordan, RREF")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would not abbreviate RREF in print output.

print(A, "\n")


if __name__ == "__main__":
main()

8 changes: 8 additions & 0 deletions contents/gaussian_elimination/gaussian_elimination.md
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,8 @@ In code, this looks like:
[import:41-78, lang:"rust"](code/rust/gaussian_elimination.rs)
{% sample lang="hs" %}
[import:10-36, lang:"haskell"](code/haskell/gaussianElimination.hs)
{% sample lang="py" %}
[import:3-28, lang:"python"](code/python/gaussian_elimination.py)
{% endmethod %}

Now, to be clear: this algorithm creates an upper-triangular matrix.
Expand Down Expand Up @@ -393,6 +395,8 @@ This code does not exist yet in rust, so here's Julia code (sorry for the inconv
[import:67-93, lang:"julia"](code/julia/gaussian_elimination.jl)
{% sample lang="hs" %}
[import:38-46, lang:"haskell"](code/haskell/gaussianElimination.hs)
{% sample lang="py" %}
[import:31-51, lang:"python"](code/python/gaussian_elimination.py)
{% endmethod %}

## Back-substitution
Expand Down Expand Up @@ -423,6 +427,8 @@ In code, this involves keeping a rolling sum of all the values we substitute in
[import:79-94, lang:"rust"](code/rust/gaussian_elimination.rs)
{% sample lang="hs" %}
[import:48-53, lang:"haskell"](code/haskell/gaussianElimination.hs)
{% sample lang="py" %}
[import:54-68, lang:"python"](code/python/gaussian_elimination.py)
{% endmethod %}

## Conclusions
Expand All @@ -445,6 +451,8 @@ As for what's next... Well, we are in for a treat! The above algorithm clearly h
[import, lang:"rust"](code/rust/gaussian_elimination.rs)
{% sample lang="hs" %}
[import, lang:"haskell"](code/haskell/gaussianElimination.hs)
{% sample lang="py" %}
[import, lang:"python"](code/python/gaussian_elimination.py)
{% endmethod %}


Expand Down