Skip to content

Instantly share code, notes, and snippets.

@wfarr
Created March 15, 2009 09:37
Show Gist options
  • Select an option

  • Save wfarr/79377 to your computer and use it in GitHub Desktop.

Select an option

Save wfarr/79377 to your computer and use it in GitHub Desktop.
def gauss_seidel(matrix,vector)
a11 = matrix[0,0]
a12 = matrix[0,1]
a21 = matrix[1,0]
a22 = matrix[1,1]
b1 = vector[0]
b2 = vector[1]
x_1 = ->(x){ b1.fdiv(a11) - (a12.fdiv(a11) * x) }
x_2 = ->(x){ b2.fdiv(a22) - (a21.fdiv(a22) * x) }
prev = 0.0
prev2 = 0.0
iter = 1
puts "=== Iteration #{iter} ==="
curr = x_1[prev2]
curr2 = x_2[curr]
puts "x1: (#{b1}/#{a11}) - ((#{a12}/#{a11}) * %.3f) = %.3f" % [prev,curr]
puts "x2: (#{b2}/#{a22}) - ((#{a21}/#{a22}) * %.3f) = %.3f" % [curr,curr2]
while (curr - prev).abs >= 0.001 && (curr2 - prev2).abs >= 0.001
iter += 1
puts "=== Iteration #{iter} ==="
prev = curr
prev2 = curr2
curr = x_1[prev2]
curr2 = x_2[curr]
puts "x1: (#{b1}/#{a11}) - ((#{a12}/#{a11}) * %.3f) = %.3f" % [prev,curr]
puts "x2: (#{b2}/#{a22}) - ((#{a21}/#{a22}) * %.3f) = %.3f" % [curr,curr2]
end
puts "result: %.3f %.3f" % [curr,curr2]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment