使用math.random()随机选择一个数字
我想选择一个范围内的随机数,但假设生成的数字是“x”,下次我想这个数字至少是x±20。我怎样才能做到这一点使用math.random()随机选择一个数字,math,random,lua,Math,Random,Lua,我想选择一个范围内的随机数,但假设生成的数字是“x”,下次我想这个数字至少是x±20。我怎样才能做到这一点 math.random只接受两个参数,因此如果依次选择1,则选择的数字为40,在第二秒内应为50或更多/30或更少,类似地,下次应为60或更多/20或更少。不知道LUA,因此我们将使用伪代码 t = Math.random(0,60); if (t > last_value - 20) t += 40 last_value = t 假设您想要一个范围为[0,L]的数字x,使
math.random只接受两个参数,因此如果依次选择1,则选择的数字为40,在第二秒内应为50或更多/30或更少,类似地,下次应为60或更多/20或更少。不知道LUA,因此我们将使用伪代码
t = Math.random(0,60);
if (t > last_value - 20)
t += 40
last_value = t
假设您想要一个范围为[0,L]的数字x,使得每个数字与Java中的前一个数字之间的循环距离至少为d:
public static double rand1(double L, double d, double x) {
double y = x + d + Math.random() * (L - 2.0 * d) ;
if (y >= L)
y -= L;
return y;
}
不允许周期性的小距离可能看起来是一个不必要的复杂问题,但实际上是一个简化:首先,这个简单的算法产生了均匀的分布[0,L,而接受的答案不是。如果有一个主对象随机放置在0和xMax之间,并且有一个或多个次对象必须放置在相同的范围内,但至少距离mainX的主对象D,并且如果有多个次对象,则次对象可以彼此靠近他们,然后试试这个:
function getRandPosNotTooCloseToMain(xMax, mainX, D)
assert(2*D < xMax) -- if false then main too "fat"
local leftLen = mainX - D
local rightLen = xMax - (mainX + D)
local leftSideWins = true -- need some default
if leftLen < 0 then -- can only place it right side of main
assert(rightLen > 0)
leftSideWins = false
elseif rightLen < 0 then -- can only place it on left side of main
-- nothing to do, because leftSideWins already true
else -- there is space on either side of main (both leftLen and rightLen > 0),
-- so randomly select one side then return random # on that side
local ratio = leftLen / (leftLen + rightLen)
if math.random() > ratio then -- right half wins
leftSideWins = false
else -- left side wins, this is the default
end
end
if leftSideWins then
return math.random(0, leftLen)
else
return mainX + D + math.random(0, rightLen)
end
end
这可以通过以下方式进行测试:
-- test
math.randomseed(os.time())
local numTests = 100000
-- generate a bunch of values for right side always wins:
for x=1,numTests do
local x = getRandPosNotTooCloseToMain(60, 15, 20)
assert( x >= 15+20, x )
end
-- generate a bunch of values for left side always wins:
for x=1,numTests do
local x = getRandPosNotTooCloseToMain(60, 45, 20)
assert( x <= 45-20, x )
end
-- generate a bunch of values for left side always wins:
for x=1,numTests do
local x = getRandPosNotTooCloseToMain(60, 30, 20)
assert( x <= 10 or x>= 50, x )
end
-- if get this far then all tests passed!
print("Passed!")
所有测试都通过。在您的情况下,您可以通过math.random0,xMax随机设置mainX。math.random只需要两个参数。如果您能通知我们编程,这将有所帮助language@leonbloy:我使用的是Lua,但math.random与大多数编程语言中的函数类似,只有1或2个参数。Summing参数是范围,I t你的意思是下一个数字应该在[x-20;x+20]之内,x是生成的最后一个数字?您能指定一个整体范围吗?例如,仅使用0到100I之间的数字,就像这一个,因为它更一般化,并且比我的答案更好:这是可行的,但与我的解决方案在两个方面不同:1:它允许小循环距离,即允许x[1]=1 x[2]=99 2:它在[0100]中没有给出均匀分布。