【发布时间】:2010-11-30 20:50:37
【问题描述】:
编写中子束的简单蒙特卡罗模拟。几何逻辑有问题(无论是在一种环境还是另一种环境中)。我的问题是 Ruby 似乎是按顺序处理条件并保留它的第一个值。
下面的代码很好地说明了这一点:
def checkPosition(*args)
polyCylRad = 2.5
polyCylFr = 15
polyCylB = -2.0
borPolyBoxL = 9.0 / 2
pbCylRad = 3.0
pbBoxL = 10.0 / 2
cdBoxL = 9.5 / 2
position = Array.new
material = String.new
args.each do |item|
position << item.inspect.to_f
end
xSquared = position.at(0) ** 2
ySquared = position.at(1) ** 2
zSquared = position.at(2) ** 2
modX = Math.sqrt(xSquared)
modY = Math.sqrt(ySquared)
modZ = Math.sqrt(zSquared)
puts xSquared
puts Math.sqrt(ySquared + zSquared) <= polyCylRad
puts (position.at(0) >= polyCylB)
puts (position.at(0) <= polyCylFr)
puts (position.at(0) >= polyCylB)and(position.at(0) <= polyCylFr)
puts (position.at(0) <= polyCylFr)and(position.at(0) >= polyCylB)
puts zSquared
polyCylinder = (Math.sqrt(ySquared + zSquared) <= polyCylRad)and((position.at(0) >= polyCylB)and(position.at(0) <= polyCylFr) )
puts polyCylinder
borPolyBox = ((modX <= borPolyBoxL)or(modY < borPolyBoxL)or(modZ <= borPolyBoxL)) and not((modX >= cdBoxL)or(modY >= cdBoxL)or(modZ >= cdBoxL)) and not(Math.sqrt(ySquared + zSquared) <= polyCylRad)
puts borPolyBox
cadmiumShield = ((modX <= cdBoxL)or(modY < cdBoxL)or(modZ <= cdBoxL)) and not((modX >= pbBoxL)or(modY >= pbBoxL)or(modZ >= pbBoxL)) and not(Math.sqrt(ySquared + zSquared) <= polyCylRad)
puts cadmiumShield
leadShield = ( ((modX <= pbBoxL)or(modY <= pbBoxL)or(modZ <= pbBoxL)) or ((position.at(0) <= ployCylFr)and(Math.sqrt(ySquared + zSquared) <= pbCylRad)) ) and not(Math.sqrt(ySquared + zSquared) <= polyCylRad)
puts leadShield
if (polyCylinder) : material = "poly"
elsif(borPolyBox) : material = "borPoly"
elsif(cadmiumSheild) : material = "cd"
elsif(leadSheild) : material = "pb"
elsif(material == nil) : position = Array.new
end
thisEnvironment = Array.new
thisEnvironment << position << material
puts thisEnvironment.at(0)
puts thisEnvironment.at(1)
end
checkPosition(40, 0, 0)
随心所欲地调用代码,但给它 *args 作为参数(我很懒,将来可能想添加更多 args)然后用 3 个浮点数调用它,在逻辑中设置几何图形,然后你会明白我的意思。
我的问题是:如何在没有一大堆嵌套 if 的情况下让它按应有的方式工作(即正确评估逻辑)? (这就是我即将重制的内容,但是阅读起来是一场噩梦,而且内存很便宜。)
【问题讨论】:
-
您能否更具体地说明您希望它如何评估逻辑?代码应该输出什么?
-
好吧,目前我只想看看赋予各个域的真值。这取决于参数数组。我的问题在第一组 puts 语句中概述,评估逻辑的顺序很重要,当它不应该 不管我是否使用 &&,|| or or and and and,这是为什么呢?我不认为是这样,但是:我正在使用 jEdit 解释器(我确信它只是在我的 PATH 中查找)。