【问题标题】:Pythonic way to "round()" like Javascript "Math.round()"?像Javascript“Math.round()”一样“round()”的Pythonic方式?
【发布时间】:2016-01-19 12:15:45
【问题描述】:

我想要最 Pythonic 的方式来对数字进行舍入,就像 Javascript 一样(通过Math.round())。它们实际上略有不同,但这种差异会对我的应用程序产生巨大的影响。

使用 Python 3 中的 round() 方法:

// Returns the value 20
x = round(20.49)

// Returns the value 20
x = round(20.5)

// Returns the value -20
x = round(-20.5)

// Returns the value -21
x = round(-20.51)

使用来自 Javascript* 的 Math.round() 方法:

// Returns the value 20
x = Math.round(20.49);

// Returns the value 21
x = Math.round(20.5);

// Returns the value -20
x = Math.round(-20.5);

// Returns the value -21
x = Math.round(-20.51);

谢谢!

参考资料:

【问题讨论】:

  • 请指定您使用的python版本,因为python 2和python 3可能不同。
  • 首先,为什么负面点没有任何解释?谢谢@khelwood,我会提供信息。
  • This question 及其答案可能会掩盖这种情况。
  • 我已更新问题以包含 Python 版本!
  • 感谢您提供链接的问题,@kazemakase。现在我明白为什么 Python3 选择以这种方式对数字进行四舍五入了。

标签: javascript python python-3.x math


【解决方案1】:
import math
def roundthemnumbers(value):
    x = math.floor(value)
    if (value - x) < .50:
        return x
    else:
        return math.ceil(value)

我还没有喝咖啡,但该功能应该可以满足您的需求。也许有一些小的修改。

【讨论】:

  • 也感谢您的回答,@JessePardue。我没有将您的问题命名为最佳问题,因为您的解决方案比其他解决方案稍微复杂一些。无论如何,谢谢你的回答!
  • 只有两个问题:(a) 为什么要返回括号内的值? (b) 为什么在退回之前存储y?直接返回值不是更好吗?
  • 我认为你想要&lt; 0.5 而不是&lt;= 0.5:确切的中途案例应该向上取整而不是向下取整。
  • 值得指出的是,在通常的 IEEE 754 规则下(例如,round-ties-to-even rounding 模式),此函数为所有输入提供正确的结果,尽管这在实现中并不完全明显.潜在的问题是value - x 可能无法精确表示,并且该减法中隐含的舍入步骤可能会改变比较结果。然而,更仔细的分析表明value - x is 完全可以表示x 而不是(-0.5, 0),对于(-0.5, 0) 中的值我们总是有value - x &gt;= 0.5,即使考虑了四舍五入.
  • 其实关于舍入方式的那一点就忽略了;这应该适用于四种标准 IEEE 754 舍入模式中的任何一种。关键观察是在麻烦区间内,value - x 的精确值严格大于0.5,因此value - x 的四舍五入值大于或等于0.5,无论是什么舍入模式。所以value 总是会被四舍五入,这是应该的。
【解决方案2】:

Python 的 round 函数的行为在 Python 2 和 Python 3 之间发生了变化。但看起来您想要以下内容,这在任一版本中都可以使用:

math.floor(x + 0.5)

这应该会产生你想要的行为。

【讨论】:

  • 请注意,此解决方案无法正确处理某些极端情况输入:示例为 0.49999999999999994(生成 1.0 而不是 0.0)、5000000000000001.0(生成5000000000000002.0)、-0.3(产生0.0 而不是-0.0)。如果您关心这些边缘情况,那么@JessePardue 的解决方案会更好。
  • 哇,谢谢@MarkDickinson 的建议。是的,第一种和第二种情况对我来说很重要,我真的很在意。我会将我的解决方案更改为 JessePardue 指出的解决方案。再次感谢您的建议!
【解决方案3】:

您可以在 python 中使用 floor 函数和 ceil 函数来完成任务,而不是在 python 中使用 round() 函数。

地板(x+0.5)

细胞(x-0.5)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多