gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 19:40:39 26 4
gpt4 key购买 nike

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 representationerror (making it possible to represent 0.1 exactly); however, someoperations can still incur round-off error when non-zero digits exceedthe fixed precision.

The effects of round-off error can be amplified by the addition orsubtraction of nearly offsetting quantities resulting in loss ofsignificance. Knuth provides two instructive examples where roundedfloating point arithmetic with insufficient precision causes thebreakdown 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/

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