Zdrojové kódy: combinatorics.rb
$colors = %w(Green Blue Red Maroon Yellow Olive Lime Gray Aqua Black Silver Teal White Navy Fuchsia Purple)
def create_pascal_triangle(n, d, filename='pascal_triangle')
svg = Svg::Svg.new width: n*10, height: n*10
triangle = PascalTriangle.new(n).pascal_triangle
for level in n.downto(1)
triangle[level-1].each_index do |number_index|
x = (n-level)*5 + number_index*10
y = (level-1)*10
color = $colors[triangle[level-1][number_index]%d]
svg.add_shape(Svg::Rectangle.new(x, y, 10, 10, {fill: color}))
end
end
svg.doc.write File.new("outputs/#{filename}.svg", 'w')
end
if __FILE__ == $0
create_pascal_triangle(150, 17, 'pascal_triangle_150x17')
end
Zdrojové kódy: task_02B.rb, pascal_triangle.rb
Zdrojové kódy: task_02C.rb, exponentiation.rb
# Monte Carlo method
def mcm_time(seconds)
seconds = seconds.to_f
number_in_circle, n = 0, 1
started_time = Time.now
while true do
n += 1
number_in_circle += 1 if Math.hypot(rand, rand) <= 1.0
elapsed_time = Time.now - started_time
return {pi: 4.0 * number_in_circle / n, elapsed_time: elapsed_time} if seconds <= elapsed_time
end
end
# Monte Carlo method:
# PI = 3.141933487103836 (Delta: -0.00034083351404268214), Elapsed seconds = 2.000040822
# Gregory-Leibniz series
def gls_time(seconds)
pi, n = 4, 1
started_time = Time.now
while true do
pi += gls_step(n)
n += 1
elapsed_time = Time.now - started_time
return {pi: pi, elapsed_time: elapsed_time} if seconds <= elapsed_time
end
end
# Gregory-Leibniz series:
# PI = 3.1415915153143232 (Delta: 1.1382754698807673e-06), Elapsed seconds = 2.000000243
# Nilakantha series
def ns_time(seconds)
seconds = seconds.to_f
pi, n = 3, 1
started_time = Time.now
while true do
pi += ns_step(n)
n += 1
elapsed_time = Time.now - started_time
return {pi: pi, elapsed_time: elapsed_time} if seconds <= elapsed_time
end
end
# Nilakantha series:
# PI = 3.141592653589787 (Delta: 6.217248937900877e-15), Elapsed seconds = 2.00000185
# Archimedes method
def as_time(seconds)
seconds = seconds.to_f
a, b, n = 4, 2*Math.sqrt(2), 1
started_time = Time.now
while true do
a, b = as_step(a, b)
n += 1
elapsed_time = Time.now - started_time
return {pi: (a + b) / 2.0, elapsed_time: elapsed_time} if seconds <= elapsed_time
end
end
# Archimedes method:
# PI = 3.1415926535897936 (Delta: -4.440892098500626e-16), Elapsed seconds = 2.000030485
Zdrojové kódy: task_02D.rb, pi.rb