Lua小数点符号?
我在其他语言中使用过这个,但是lua似乎缺少这个相当有用的功能。
你们中的一位好心人能给我提供一个 lua 函数来获取传递给它的数字的符号吗?
I've used this in other languages, but lua seems to be lacking this rather useful function.
Could one of you nice chappies provide me a lua function to get the sign of the number passed to it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
以防万一有人偶然发现这个:这是我的较短版本:
Just in case anyone stumbles on this one:, here's my somehow shorter version:
我认为这个想法是返回 1 或 -1 来代表正数或负数。我认为你不希望它返回 0。可能会产生灾难性的影响。想象一下,当值返回 0 时,尝试通过将其乘以符号(x)来更改值的符号。您可以将值更改为 0,而不是更改符号。
我会坚持使用
I think the idea is to return 1 or -1 to represent positive or negative. I don't think you would want it to return 0. Could have disastrous effects. Imagine trying to change the sign of a value by multiplying it by sign(x) when it returns 0. Instead of changing the sign you'd change the value to 0.
I'd stick with
使用 LuaJIT,如果符号函数得到 JIT 编译,这实际上会更快:
原因是它避免了分支,而分支的成本可能很高。即使输入在非正规范围内,双重乘法也可确保结果正确。不能使用无穷大,因为输入为零时会产生 NaN。
仅在 x86 中测试。我不能保证它是 LuaJIT 支持的其他处理器中最快的。
With LuaJIT, if the sign function gets JIT-compiled, this is actually faster:
The reason is that it avoids branches, which can be expensive. The double multiplication ensures that the result is correct even with inputs in the denormal range. Infinity can't be used because with an input of zero, it would produce NaN.
Tested in x86 only. I can't guarantee that it's the fastest in other processors supported by LuaJIT.
我构建这个版本是因为我需要精确处理
-0
和+0
以及nan
,而所有其他版本都无法处理。这个想法是直接解释符号位并为该测试提供无分支版本。在纯 Lua 中,你必须使用 tostring(x) 检查 +-0。
I built this one because I needed exact handling for
-0
and+0
as well as fornan
which all the other versions do not handle.The idea is to interpret the sign bit directly and have a branchless version for this test. In pure Lua you'd have to go with tostring(x) checks +-0.
你还可以像这样得到一个数字的符号:
我只将它用于整数,并且由于 Lua 不区分整数和浮点数,所以我根本不会在 Lua 中使用它。
You can also get the sign of a number like this:
I'd only use that one for integers and since Lua doesn't distinguish ints from floats, I'd not use it in Lua at all.
的变体在
数学上,符号是“+”或“-”(符号),而不是数字(如+1或-1)
A variation of that could be
Mathematically, the sign is '+' or '-' (a symbol), not a number (as +1 or -1)
您可以像这样检查
sign
:You can check for the
sign
like this: