Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby script to draw a lorenz attractor with Euler's method.
#! /usr/local/bin/ruby
# *******************************
# Lorenz attractor (Euler method)
# *******************************
#
require 'numo/gnuplot'
class LorenzAttractorEuler
DT = 1e-3 # Differential interval
STEP = 100000 # Time step count
X_0, Y_0, Z_0 = 1, 1, 1 # Initial values of x, y, z
def initialize
@res = [[], [], []]
end
def exec
xyz = [X_0, Y_0, Z_0]
STEP.times do
l = lorenz(xyz)
3.times do |i|
xyz[i] += DT * l[i]
@res[i] << xyz[i]
end
end
plot
rescue => e
$stderr.puts "[#{e.class}] #{e.message}"
e.backtrace.each { |tr| $stderr.puts "\t#{tr}" }
exit 1
end
private
def lorenz(xyz, p=10, r=28, b=8/3.0)
return [
-p * xyz[0] + p * xyz[1],
-xyz[0] * xyz[2] + r * xyz[0] - xyz[1],
xyz[0] * xyz[1] - b * xyz[2]
]
rescue => e
raise
end
def plot
x, y, z = @res
begin
Numo.gnuplot do
set terminal: "png"
set output: "lorenz_attractor_euler.png"
set title: "Lorenz attractor (Euler method)"
set xlabel: "x"
set ylabel: "y"
set zlabel: "z"
unset :key
splot x, y, z, with: :lines, linecolor: {rgb: "blue"}
end
rescue => e
raise
end
end
end
exit 0 unless __FILE__ == $0
LorenzAttractorEuler.new.exec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.