math - 为什么math.random(999999999999)在Lua中返回1?

标签 math random lua

我刚刚尝试过:print(math.random(999999999999)),它打印了1

此外,任何包含 999999999999math.random() 都会打印相同的内容。一些例子:

print(math.random(1.999999999999)) » 1

print(math.random(1999999999999)) » 1

for k,v in next,{math.random(999999999999), math.random(1999999999999), math.random(2.999999999999)} do
    print(v)
end

» 1

local n = math.random(999999999999)
print(n==1)

» true

那么我想你明白了(当然如果你了解 Lua)。你能解释一下吗?

@编辑:

我使用的Lua版本是5.2。

我还尝试了print(math.random(-999999999999)),它打印了111711452。看起来它是一个正数。

最佳答案

这个问题肯定是因为 math.random 处理 Lua 5.1 和/或 5.2 中传递的输入参数。来自[mathlib.c] 1 :

正如您在 C 中所知,标准 int 可以表示值 -2,147,483,6482,147,483,647。将 +1 添加到 2,147,483,647 中,就像在您的用例中一样,将会溢出并环绕给出 -2,147,483,648 的值。最终结果是负数,因为您将正数与负数相乘。

有几种方法可以纠正和处理此问题:

  1. 升级到最新的 Lua 版本 5.3 。此后,该人通过将输入参数视为 lua_Number 解决了此问题。
  2. 切换到没有此整数溢出问题的 LuaJIT。
  3. 自行修补 Lua 5.1 和/或 5.2 源代码并重新编译。
  4. 修改随机范围,使其不会溢出

对于您的最后一个查询,请阅读 documentation

注意最后一行引号:

math.random(upper) generates integer numbers between 1 and upper.upper and lower must be integer. In other case Lua casts upper into an integer, sometimes giving math.floor(upper) and others math.ceil(upper), with unexpected results (the same for lower).

关于math - 为什么math.random(999999999999)在Lua中返回1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45680884/

相关文章:

javascript - 以编程方式在圆形路径中创建 SVG 圆,与对象保持均匀距离

python - 在 Python 中生成随机的 6 位数字 ID

c - 使用 Mersenne twister 在 C 中生成随机数

javascript - Javascript 中 float 的精度可以成为非确定性的来源吗?

php - 如何向下舍入到php中最接近的有效数字

c++ - 不用 cmath 计算 sin

lua - 某些 Computercraft/lua 代码遇到问题

c++ - 为什么线程随机这么慢,-(或者我的代码哪里错了!)

objective-c - 来自脚本语言(Lua、Ruby 等)的 Cocoa 桥是否需要 MacOS 上的编译部分才能工作?

java - 使用 LuaJ 推送 int