Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active April 19, 2018 05:24
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 komasaru/6519428 to your computer and use it in GitHub Desktop.
Save komasaru/6519428 to your computer and use it in GitHub Desktop.
Ruby script to solve simultaneous equations with Gauss-Jorden(pivot) method.
#! /usr/local/bin/ruby
#***********************************************************
# 連立方程式の解法 ( ガウス・ジョルダン(ピボット選択)法 )
#***********************************************************
#
class GaussJordenPivot
def initialize
# 係数
@a = [
#[ 2, -3, 1, 5],
#[ 1, 1, -1, 2],
#[ 3, 5, -7, 0]
[ 1, -2, 3, -4, 5],
[-2, -5, -8, -3, -9],
[ 5, 4, 7, 1, -1],
[ 9, 7, 3, 5, 4]
]
# 次元の数
@n = @a.size
end
# 計算・結果出力
def exec
# 元の連立方程式をコンソール出力
display_equations
@n.times do |k|
# 行入れ替え
max, s = 0, k
k.upto(@n - 1) do |j|
next unless @a[j][k].abs > max
max = @a[j][k].abs
s = j
end
if max == 0
puts "解けない!"
exit 1
end
(@n + 1).times do |j|
dummy = @a[k][j]
@a[k][j] = @a[s][j]
@a[s][j] = dummy
end
# ピボット係数
p = @a[k][k]
# ピボット行を p で除算
k.upto(@n) { |j| @a[k][j] /= p.to_f }
# ピボット列の掃き出し
@n.times do |i|
next if i == k
d = @a[i][k]
k.upto(@n) { |j| @a[i][j] -= d * @a[k][j] }
end
end
# 結果出力
display_answers
rescue => e
raise
end
private
# 元の連立方程式をコンソール出力
def display_equations
@n.times do |i|
@n.times { |j| printf("%+dx%d ", @a[i][j], j + 1) }
puts "= %+d" % @a[i][@n]
end
rescue => e
raise
end
# 結果出力
def display_answers
@n.times { |k| puts "x%d = %f" % [k + 1, @a[k][@n]] }
rescue => e
raise
end
end
if __FILE__ == $0
begin
# 計算クラスインスタンス化
obj = GaussJordenPivot.new
# 連立方程式を解く(ガウス・ジョルダン(ピボット選択)法)
obj.exec
rescue => e
$stderr.puts "[#{e.class}] #{e.message}"
e.backtrace.each{ |tr| $stderr.puts "\t#{tr}" }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment