Advertisement
cd62131

Runge-Kutta with y = exp(x^2), y' = 2 x y, x: 0 to 1

Nov 26th, 2013
389
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.46 KB | None | 0 0
  1. #!/usr/bin/ruby
  2. # coding: utf-8
  3. def df(x, y) 2 * x * y end
  4. n = 128
  5. ret = []
  6. ret << [0.0, 1.0]
  7. h = 1.0 / n
  8. n.times do |i|
  9.   k1 = h * df(ret[i][0], ret[i][1])
  10.   k2 = h * df(ret[i][0] + h / 2, ret[i][1] + k1 / 2)
  11.   k3 = h * df(ret[i][0] + h / 2, ret[i][1] + k2 / 2)
  12.   k4 = h * df(ret[i][0] + h, ret[i][1] + k3)
  13.   ret << [(i + 1) * h, ret[i][1] + (k1 + 2 * k2 + 2 * k3 + k4) / 6]
  14. end
  15. open('outpu.dat', 'w') do |f|
  16.   ret.each {|x, y| f.puts "#{x} #{y}"}
  17. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement