Zmodyfikowana metoda monte carlo

  -TMOVE_BUTT AMOVE_BUTT SMOVE_BUTT
User avatar
Chameleon
bywalec
Posts: 616
Joined: Fri Aug 04, 2017 3:49 pm
płeć: mężczyzna

Zmodyfikowana metoda monte carlo

Postby Chameleon » Sun Feb 04, 2018 3:50 pm

def calka(aprox, x_min, x_max)
eq = ->(x) {-x**3 * (x + 1)}

xs = x_min.to_f
xe = x_max.to_f
ys = 0.0
ye = 0.0

dx = (xe - xs.to_f) / aprox
result = 0.0
logic = true
0..aprox.times do |time|
dist = xs + time * dx
point_0 = dist
point_1 = dist + dx
ye = [0.0, 0.0]
ye[0] = eq.call(point_0)
ye[1] = eq.call(point_1)
ye = ye.max * 2
rang = 0.0
if ys <= ye
logic = true
rang = ys..ye
else
logic = false
rang = ye..ys
end
in_points = 0.0
0..aprox.times do
r0 = Random.new
r1 = Random.new
r0 = r0.rand(point_0...point_1)
r1 = r1.rand(rang)

if logic == true && r1 <= eq.call(r0) && r1 > 0
in_points += eq.call(r0) * dx
elsif logic == false && r1 >= eq.call(r0) && r1 < 0
in_points += eq.call(r0) * dx
end
end
result += in_points / aprox * 2
end
result
end

test_val_min = 0
test_val_max = 10

p calka(100, test_val_min, test_val_max)

test = Array.new
20.times do |t|
test << calka(100, test_val_min, test_val_max)
p "Test nr " + (t + 1).to_s
end
p test.inject(:+) / 20.0

Return to “informatyka”

Who is online

Users browsing this forum: CommonCrawl [Bot], Google [Bot] and 1 guest