Created
March 22, 2018 05:06
-
-
Save komasaru/0e9ec99ceb90145ed56bd7fbb211f436 to your computer and use it in GitHub Desktop.
Ruby script to draw a lorenz attractor with Euler's method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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