我正在尝试计算 pi 并将其放入 ruby 中的图片中。它一直工作到第 36 行(它不将 pi [没有小数位] 写入文件)和第 63 行(它只将白色写入 pi.png)。附带说明一下,该程序似乎没有生成正确的 pi ( $looptimes
)位数
这是我的红宝石文件:
pi.rb
#get width and height of picture
p 'width of pi'
$w = gets.chomp.to_i
p 'height of pi'
$h = gets.chomp.to_i
$looptimes = $w*$h
#calculate pi
def pi
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
dot = nil
$looptimes.times do
if 4*q+r-t < n*t
yield n
nr = 10*(r-n*t)
n = ((10*(3*q+r)) / t) - 10*n
q *= 10
r = nr
else
nr = (2*q+r) * l
nn = (q*(7*k+2)+r*l) / (t*l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
end
end
end
#create and write to file
File.new("pi.txt", 'w')
File.open("pi.txt", 'w') { |pitxt|
pitxt.write(pi {|digit| print digit; $stdout.flush})}
def read_file(file_name)
file = File.open(file_name, "r")
data = file.read
file.close
return data
end
pinumber = read_file("./pi.txt")
pinumber.to_s
require 'chunky_png'
#make picture
image = ChunkyPNG::Image.new($w,$h)
image.save('pi.png')
image = ChunkyPNG::Image.from_file('pi.png')
#draw pixels
for $pointw in 0...$w do
for $pointh in 0...$h do
for j in 0...$looptimes do
if pinumber[j] = '0'
image[$pointw,$pointh] = ChunkyPNG::Color.rgb(244,244,244)
image.save('pi.png')
elsif pinumber[j] = '1'
image[$pointw,$pointh] = ChunkyPNG::Color.rgb(231,47,39)
image.save('pi.png')
elsif pinumber[j] = '2'
image[$pointw,$pointh] = ChunkyPNG::Color.rgb(241,176,102)
image.save('pi.png')
elsif pinumber[j] = '3'
image[$pointw,$pointh] = ChunkyPNG::Color.rgb(255,228,15)
image.save('pi.png')
elsif pinumber[j] = '4'
image[$pointw,$pointh] = ChunkyPNG::Color.rgb(18,154,47)
image.save('pi.png')
elsif pinumber[j] = '5'
image[$pointw,$pointh] = ChunkyPNG::Color.rgb(126,188,209)
image.save('pi.png')
elsif pinumber[j] = '6'
image[$pointw,$pointh] = ChunkyPNG::Color.rgb(3,86,155)
image.save('pi.png')
elsif pinumber[j] = '7'
image[$pointw,$pointh] = ChunkyPNG::Color.rgb(46,20,141)
image.save('pi.png')
elsif pinumber[j] = '8'
image[$pointw,$pointh] = ChunkyPNG::Color.rgb(152,152,152)
image.save('pi.png')
elsif pinumber[j] = '9'
image[$pointw,$pointh] = ChunkyPNG::Color.rgb(10,10,10)
image.save('pi.png')
end
end
end
end
如果您有任何想法,请告诉我。
另外,有没有更有效的方法来做到这一点?谢谢大家的帮助!