[Ruby] 루비에서 그래프 구현하기 (gnuplot 설치)
gnuplot
가 설치가 되었다면 간단하게 sin
그래프를 구현해보았습니다.
x변수에 [-5.0, -4.9, -4.8, ... 4.8, 4.9, 5.0]리스트를 생성하고 y변수에는 x 리스트에 값들의 sin값을 구한 값의 리스트를 넣어 주어서 그래프를 그려보았습니다. 정확한 값을 위해 0.1씩 증가할때 round로 소수점 1자리까지 나오게 하였는데요.
특정 구간에서 -3.5999999999999996
와 다들 이시는 컴퓨터 저장 방식에 따른 부동소수점
의 문제가 발생하기 때문에 정확한 값을 저장하기 위해서 반올림을 하였습니다.
x = (-5..5).step(0.1).collect { |v| v.to_f }
puts x.join(" ")
출력
-5.0 -4.9 -4.8 -4.7 -4.6 -4.5 -4.4 -4.3 -4.2 -4.1 -4.0 -3.9 -3.8 -3.7 -3.5999999999999996 -3.5 -3.4 -3.3 -3.2 -3.0999999999999996 -3.0 -2.9 -2.8 -2.6999999999999997 -2.5999999999999996 -2.5 -2.4 -2.3 -2.1999999999999997 -2.0999999999999996 -2.0 -1.9 -1.7999999999999998 -1.6999999999999997 -1.5999999999999996 -1.5 -1.4 -1.2999999999999998 -1.1999999999999997 -1.0999999999999996 -1.0 -0.8999999999999995 -0.7999999999999998 -0.7000000000000002 -0.5999999999999996 -0.5 -0.39999999999999947 -0.2999999999999998 -0.1999999999999993 -0.09999999999999964 0.0 0.10000000000000053 0.20000000000000018 0.3000000000000007 0.40000000000000036 0.5 0.6000000000000005 0.7000000000000002 0.8000000000000007 0.9000000000000004 1.0 1.1000000000000005 1.2000000000000002 1.3000000000000007 1.4000000000000004 1.5 1.6000000000000005 1.7000000000000002 1.8000000000000007 1.9000000000000004 2.0 2.1000000000000005 2.2 2.3000000000000007 2.4000000000000004 2.5 2.6000000000000005 2.7 2.8000000000000007 2.9000000000000004 3.0 3.0999999999999996 3.200000000000001 3.3000000000000007 3.4000000000000004 3.5 3.5999999999999996 3.700000000000001 3.8000000000000007 3.9000000000000004 4.0 4.1 4.200000000000001 4.300000000000001 4.4 4.5 4.600000000000001 4.700000000000001 4.800000000000001 4.9 5.0
x = (-5..5).step(0.1).collect { |v| v.to_f.round(1) }
puts x.join(" ")
출력
-5.0 -4.9 -4.8 -4.7 -4.6 -4.5 -4.4 -4.3 -4.2 -4.1 -4.0 -3.9 -3.8 -3.7 -3.6 -3.5 -3.4 -3.3 -3.2 -3.1 -3.0 -2.9 -2.8 -2.7 -2.6 -2.5 -2.4 -2.3 -2.2 -2.1 -2.0 -1.9 -1.8 -1.7 -1.6 -1.5 -1.4 -1.3 -1.2 -1.1 -1.0 -0.9 -0.8 -0.7 -0.6 -0.5 -0.4 -0.3 -0.2 -0.1 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 3.0 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 4.0 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 5.0
require 'gnuplot'
Gnuplot.open do |g|
Gnuplot::Plot.new(g) do |plot|
x = (-5..5).step(0.1).collect { |v| v.to_f.round 1 }
y = x.collect { |v| Math.sin v }
plot.data << Gnuplot::DataSet.new([x, y]) do |d|
d.with = "lines"
d.linewidth = 2
end
end
end