Python:十进制加法和减法没有给出确切的结果

标签 python decimal precision

Python (3.8) 代码:

#!/usr/bin/env python3

from decimal import Decimal
from decimal import getcontext

x = Decimal('0.6666666666666666666666666667')
y = x;
print(getcontext().prec)
print(y)
print(y == x)
y += x; y += x; y += x;
y -= x; y -= x; y -= x;
print(y)
print(y == x)
python 输出:
28
0.6666666666666666666666666667
True
0.6666666666666666666666666663
False

java 代码:
import java.math.BigDecimal;

public class A
{
    public static void main(String[] args)
    {
        BigDecimal x = new BigDecimal("0.6666666666666666666666666667");
        BigDecimal y = new BigDecimal("0.6666666666666666666666666667");

        System.out.println(x.precision());
        System.out.println(y.precision());

        System.out.println(y);
        System.out.println(y.equals(x));

        y = y.add(x); y = y.add(x); y = y.add(x);
        y = y.subtract(x); y = y.subtract(x); y = y.subtract(x);

        System.out.println(y);
        System.out.println(y.equals(x));
    }
}
Java输出:
28
28
0.6666666666666666666666666667
true
0.6666666666666666666666666667
true
在 Python 中实现任意精度的方法是什么?通过设置一个非常大的prec ?

最佳答案

来自 the Decimal docs :

The use of decimal floating point eliminates decimal representation error (making it possible to represent 0.1 exactly); however, some operations can still incur round-off error when non-zero digits exceed the fixed precision.

The effects of round-off error can be amplified by the addition or subtraction of nearly offsetting quantities resulting in loss of significance. Knuth provides two instructive examples where rounded floating point arithmetic with insufficient precision causes the breakdown of the associative and distributive properties of addition:

# Examples from Seminumerical Algorithms, Section 4.2.2.
>>> from decimal import Decimal, getcontext
>>> getcontext().prec = 8

>>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
>>> (u + v) + w 
Decimal('9.5111111')
>>> u + (v + w) 
Decimal('10')

>>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
>>> (u*v) + (u*w) 
Decimal('0.01')
>>> u * (v+w) 
Decimal('0.0060000') 

关于Python:十进制加法和减法没有给出确切的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65167576/

相关文章:

c++ - 给定很长的二进制,将其转换为十进制

javascript - JS中整数除法的精确性

java - 在 Java 中以可变精度(不四舍五入)打印 double

python - 如何在python中的字典中获取键的位置

Python:为模块及其导入设置 __globals__

python:使用不正确的导入语句导入模块=>来自生成的 ImportError 的不详尽信息

python - python 2.x 和 3.x 之间的多线程开销差异

postgresql - 在postgresql中划分大数

c++ - 如何在 C++ 中将 double 转换为 C# 小数?

c# - 我应该担心这个 DateTime 数学会失去精度吗?