gpt4 book ai didi

java - 舍入数字 : Java's 'Math.rint' in Python

转载 作者:行者123 更新时间:2023-11-29 06:01:34 26 4
gpt4 key购买 nike

Python 中是否存在与 Java 的 Math.rint 类似的东西?如果不是,我怎样才能达到相同的结果?

最佳答案

这里是 Python 2 的 rint 的完全相似的工作方式:

def rint(num):
"""Rounds toward the even number if equidistant"""
return round(num + (num % 2 - 1 if (num % 1 == 0.5) else 0))

print rint(-1.4) == -1.0
print rint(-1.5) == rint(-2.0) == rint(-2.5) == -2.0
print rint(1.4) == 1.0
print rint(1.5) == rint(2.0) == rint(2.5) == 2.0

在 Python 3 中,round rounds toward even就像 rint(感谢@lvc),但在 Python 2 上:

round(x[, n])

Return the floating point value x rounded to n digits after the decimal point. If n is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0).

Note

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

关于java - 舍入数字 : Java's 'Math.rint' in Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9921057/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com