Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created April 13, 2022 07:16
Show Gist options
  • Save komasaru/edadff6eaec99b807039d53aeb496b7f to your computer and use it in GitHub Desktop.
Save komasaru/edadff6eaec99b807039d53aeb496b7f to your computer and use it in GitHub Desktop.
Ruby script to solve simultaneous equations with Gauss elimination method(pivot).
#! /usr/local/bin/ruby
#*********************************************
# 連立方程式の解法 ( ガウスの消去法(ピボット選択) )
#*********************************************
#
class GaussElimination
def initialize
# 係数
@a = [
[1.0, 2.0, 7.0, 6.0, 6.0],
[2.0, 4.0, 4.0, 2.0, 2.0],
[1.0, 8.0, 5.0, 2.0, 12.0],
[2.0, 4.0, 3.0, 3.0, 5.0]
]
# 次元の数
@n = @a.size
end
# 計算・結果出力
def exec
# 元の連立方程式をコンソール出力
display_equations
# 前進消去
(@n - 1).times do |k|
raise unless pivot(k)
(k + 1).upto(@n - 1) do |i|
d = @a[i][k] / @a[k][k].to_f
(k + 1).upto(@n) do |j|
@a[i][j] -= @a[k][j] * d
end
end
end
# 後退代入
(@n - 1).downto(0) do |i|
d = @a[i][@n]
(i + 1).upto(@n - 1) do |j|
d -= @a[i][j] * @a[j][@n]
end
@a[i][@n] = d / @a[i][i].to_f
end
# 結果出力
display_answers
rescue => e
raise
end
private
# ピボット選択
def pivot(k)
pv = k
v_max = @a[k][k].abs
(k + 1).upto(@n - 1) do |i|
if @a[i][k].abs > v_max
pv = i
v_max = @a[i][k]
end
end
if k != pv
dummy = @a[k]
@a[k] = @a[pv]
@a[pv] = dummy
end
return true
rescue => e
return false
end
# 元の連立方程式をコンソール出力
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
0.upto(@n - 1) { |k| puts "x%d = %f" % [k + 1, @a[k][@n]] }
rescue => e
raise
end
end
if __FILE__ == $0
begin
obj = GaussElimination.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