Skip to content

Instantly share code, notes, and snippets.

@sahglie
Created February 28, 2011 03:09
Show Gist options
  • Save sahglie/846883 to your computer and use it in GitHub Desktop.
Save sahglie/846883 to your computer and use it in GitHub Desktop.
Simple program to approximate y if have dy/dt
def eulers_method(range, h, t, y, &block)
calculations = []
calculations << [t, y]
while t <= range.last
slope = yield(t, y)
yn = y + (slope * h)
y = yn
t += h
calculations << [t, yn]
end
calculations
end
def gather_values(approximations, points)
values = []
points.each do |point|
approximations.each_with_index do |approx, i|
if approx[0] >= point
values << approximations[i]
break
end
end
end
values
end
def print_table(data, sample_points, step_sizes)
data = data.transpose
cols = step_sizes.unshift("t").map(&:to_s)
horiz_border = "-"*((cols.length + 1) + (cols.length*9))
puts horiz_border
cols.each do |col|
print "| "
print col.to_s.ljust(8, " ")
end
puts "|"
puts horiz_border
sample_points.each_with_index do |t, i|
print "| "
print t.to_s.ljust(8, " ")
data[i].each do |val|
print "| "
print val.to_s[0, 6].ljust(8, " ")
end
puts "|"
end
puts horiz_border
end
if __FILE__ == $PROGRAM_NAME
sample_points = [1.0, 1.5, 2, 2.5, 3.0]
step_sizes = [0.1, 0.05, 0.025, 0.01, 0.001, 0.00001]
data = step_sizes.inject([]) do |accum, step|
result = eulers_method(1..3, step, 1, 2) { |t, y|
((y**2)+(2*t*y))/(3+t**2)
}
accum << gather_values(result, sample_points).map { |pair| pair[1] }
end
print_table(data, sample_points, step_sizes)
end
# -----------------------------------------------------------------------
# | t | 0.1 | 0.05 | 0.025 | 0.01 | 0.001 | 1.0e-05 |
# -----------------------------------------------------------------------
# | 1.0 | 2 | 2 | 2 | 2 | 2 | 2 |
# | 1.5 | 3.3489 | 3.4188 | 3.5641 | 3.4827 | 3.5025 | 3.4999 |
# | 2 | 6.1636 | 6.5287 | 7.0069 | 6.8947 | 7.0001 | 6.9998 |
# | 2.5 | 13.019 | 16.676 | 17.463 | 18.048 | 18.452 | 18.499 |
# | 3.0 | 38.670 | 84.760 | 140.78 | 287.01 | 1948.1 | 107106 |
# -----------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment