简体   繁体   English

半数甚至十进制

[英]Round half to even on decimal

R by default uses round half to even on the round() function. 默认情况下,R在round()函数中使用舍入的一半 But it not seems to be always true when rounding to a defined number of decimal places: 但是当舍入到定义的小数位数时似乎并不总是这样:

# R code
round(1.225,2)
#[1] 1.23
round(1.2225,3)
#[1] 1.222
round(1.22225,4)
#[1] 1.2223
round(1.222225,5)
#[1] 1.22222

Comparing to python, using the decimal module: 与python相比,使用十进制模块:

# Python code
import decimal
a = decimal.Decimal("1.225")
b = decimal.Decimal("1.2225")
c = decimal.Decimal("1.22225")
d = decimal.Decimal("1.222225")

a.quantize(decimal.Decimal('1.00'), decimal.ROUND_HALF_EVEN)
#Decimal('1.22')
b.quantize(decimal.Decimal('1.000'), decimal.ROUND_HALF_EVEN)
#Decimal('1.222')
c.quantize(decimal.Decimal('1.0000'), decimal.ROUND_HALF_EVEN)
#Decimal('1.2222')
d.quantize(decimal.Decimal('1.00000'), decimal.ROUND_HALF_EVEN)
#Decimal('1.22222')

From python decimal library docs, about quantize function: 从python十进制库文档,关于量化函数:

Return a value equal to the first operand after rounding and having the exponent of the second operand. 舍入后返回一个等于第一个操作数的值,并具有第二个操作数的指数。

I'm not sure if I'm right, but looks like the python result is correct. 我不确定我是否正确,但看起来python结果是正确的。

Question: 题:

Which one is correct, and how to achieve the correct results using the two languages? 哪一个是正确的,以及如何使用这两种语言实现正确的结果?

The problem is the finite precision of floating point values: 问题是浮点值的有限精度:

>>> '%.18f' % 1.225
'1.225000000000000089'
>>> '%.18f' % 1.2225
'1.222499999999999920'
>>> '%.18f' % 1.22225
'1.222250000000000059'
>>> '%.18f' % 1.222225
'1.222224999999999895'

Pythons Decimal-class is exact in this sense. Pythons Decimal-class在这个意义上是准确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM