Ruby実用例 〜スプライン補間〜
をテンプレートにして作成
home
>
サイトマップ
開始行:
飛び飛びの点を滑らかにつなぐ「3次スプライン補完」という方...
* コード [#l803edb2]
** spline.rb [#cb602618]
class Spline
# 初期化.3次スプライン補間曲線を求める
def initialize(x, y)
@x = x
@y = y
@z = []
n = @x.length
h = []
d = []
@z[0] = @z[n-1] = 0
for i in 0...n-1
h[i ] = @x[i+1] - @x[i]
d[i+1] = (@y[i+1] - @y[i]) / h[i]
end
@z[1] = d[2] - d[1] - h[0] * @z[0]
d[1] = 2 * (@x[2] - @x[0])
for i in 1...n-2
t = h[i] / d[i]
@z[i+1] = d[i+2] - d[i+1] - @z[i] * t
d[i+1] = 2 * (@x[i+2] - @x[i]) - h[i] * t
end
@z[n-2] -= h[n-2] * @z[n-1]
i = n - 2
while i > 0
@z[i] = (@z[i] - h[i] * @z[i+1]) / d[i]
i -= 1
end
end
# 補間値を返すメソッド
def interpolate(t)
i = 0
j = @x.length - 1
while i < j
k = (i + j) / 2
if (@x[k] < t)
i = k + 1
else
j = k
end
end
if i > 0
i -= 1
end
h = @x[i+1] - @x[i]
d = t - @x[i]
return (((@z[i+1] - @z[i]) * d / h + @z[i] * 3) * d ...
end
end
** getSpline.rb [#t7a61856]
#!/usr/bin/env ruby
org_path = File::dirname(__FILE__)
$:.unshift(org_path.untaint)
require 'spline'
x = [1, 2, 3, 4, 5]
y = [2.0, 1.1, 2.4, 3.2, 5.9]
curve = Spline.new(x, y)
i = 1.0
while i <= 5.0
printf("%f,%f\r\n", i, curve.interpolate(i))
i += 0.1
end
* 結果 [#xc7e161d]
結果をグラフで示します.まず,与えた点はつぎのものです.
#ref(fig1.png,nolink)
これらの点の間を,上のプログラムで補完した点が以下です.
#ref(fig2.png,nolink)
両者を重ねると,全ての点が滑らかにつながれていることが分...
#ref(fig3.png,nolink)
終了行:
飛び飛びの点を滑らかにつなぐ「3次スプライン補完」という方...
* コード [#l803edb2]
** spline.rb [#cb602618]
class Spline
# 初期化.3次スプライン補間曲線を求める
def initialize(x, y)
@x = x
@y = y
@z = []
n = @x.length
h = []
d = []
@z[0] = @z[n-1] = 0
for i in 0...n-1
h[i ] = @x[i+1] - @x[i]
d[i+1] = (@y[i+1] - @y[i]) / h[i]
end
@z[1] = d[2] - d[1] - h[0] * @z[0]
d[1] = 2 * (@x[2] - @x[0])
for i in 1...n-2
t = h[i] / d[i]
@z[i+1] = d[i+2] - d[i+1] - @z[i] * t
d[i+1] = 2 * (@x[i+2] - @x[i]) - h[i] * t
end
@z[n-2] -= h[n-2] * @z[n-1]
i = n - 2
while i > 0
@z[i] = (@z[i] - h[i] * @z[i+1]) / d[i]
i -= 1
end
end
# 補間値を返すメソッド
def interpolate(t)
i = 0
j = @x.length - 1
while i < j
k = (i + j) / 2
if (@x[k] < t)
i = k + 1
else
j = k
end
end
if i > 0
i -= 1
end
h = @x[i+1] - @x[i]
d = t - @x[i]
return (((@z[i+1] - @z[i]) * d / h + @z[i] * 3) * d ...
end
end
** getSpline.rb [#t7a61856]
#!/usr/bin/env ruby
org_path = File::dirname(__FILE__)
$:.unshift(org_path.untaint)
require 'spline'
x = [1, 2, 3, 4, 5]
y = [2.0, 1.1, 2.4, 3.2, 5.9]
curve = Spline.new(x, y)
i = 1.0
while i <= 5.0
printf("%f,%f\r\n", i, curve.interpolate(i))
i += 0.1
end
* 結果 [#xc7e161d]
結果をグラフで示します.まず,与えた点はつぎのものです.
#ref(fig1.png,nolink)
これらの点の間を,上のプログラムで補完した点が以下です.
#ref(fig2.png,nolink)
両者を重ねると,全ての点が滑らかにつながれていることが分...
#ref(fig3.png,nolink)
ページ名:
home
>
Modified by
物理のかぎプロジェクト
PukiWiki 1.4.5_1
Copyright © 2001-2005
PukiWiki Developers Team
. License is
GPL
.
Based on "PukiWiki" 1.3 by
yu-ji
Powered by PHP 5.3.29HTML convert time to 0.002 sec.