Round and a half even on decimal

R uses the round half by default, and even in the round() function. But this is not always true when rounding to a certain 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 

Comparison with python using decimal module:

 # 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, quantize :

Returns a value equal to the first operand after rounding and having the exponent of the second operand.

I'm not sure I'm right, but it looks like the python result is correct.

Question:

Which one is correct, and how to achieve the correct results using two languages?

+3
source share
1 answer

The problem is the final precision of the 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 is exact in that sense.

+7
source

Source: https://habr.com/ru/post/1207081/


All Articles