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/6505181 to your computer and use it in GitHub Desktop.
Save komasaru/6505181 to your computer and use it in GitHub Desktop.
Ruby script to solve simultaneous equations with Gauss-Jorden method.
#! /usr/local/bin/ruby
#*********************************************
# 連立方程式の解法 ( ガウス・ジョルダン法 )
#*********************************************
#
class GaussJorden
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|
# ピボット係数
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
0.upto(@n - 1) do |i|
0.upto(@n - 1) {|j| printf("%+dx%d ", @a[i][j], j + 1)}
printf("= %+d\n", @a[i][@n])
end
rescue => e
raise
end
# 結果出力
def display_answers
0.upto(@n - 1) {|k| printf("x%d = %f\n", k + 1, @a[k][@n])}
rescue => e
raise
end
end
if __FILE__ == $0
begin
# 計算クラスインスタンス化
obj = GaussJorden.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