Skip to content

Instantly share code, notes, and snippets.

@adeishs
Created December 24, 2023 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adeishs/62470dbb851b3ff7cb451c72c6c2c585 to your computer and use it in GitHub Desktop.
Save adeishs/62470dbb851b3ff7cb451c72c6c2c585 to your computer and use it in GitHub Desktop.
Gauss–Jordan Elimination
require 'bigdecimal'
def gj_elim(els)
h = 0
k = 0
m = els.size
n = els.first.size
# form row-echelon matrix
while h < m && k < n
unless els[h][k].zero?
[*(h + 1)...m].each do |i|
f = BigDecimal(els[i][k]) / els[h][k]
els[i][k..] = (k...n).map { |j| j == k ? 0 : els[i][j] - els[h][j] * f }
end
h += 1
end
k += 1
end
# back-substitution
[*0...m].reverse.each do |i|
t = els[i][n - 1]
[*(i + 1)...m].each do |j|
t -= els[i][j] * els[j][n - 1]
els[i][j] = 0
end
els[i][n - 1] = t / els[i][i]
els[i][i] = 1
end
els.map { |rows| rows.map(&:to_f) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment