我是Python的新手,在Python的Decimal模块中使用decimal函数时遇到了问题。我知道,由于Python将浮点值存储在内存中的方式,为了对它们执行计算以生成人类可读的结果,我们可以对结果使用round函数或使用decimal.Decimal()函数。
在下面的代码中,我创建了一个calc1类,它只返回两个数字的相加和差。然而,每当我运行它时,即使我在代码中包含了decimal.Decimal(),结果仍然是不舍入的。
代码:
import decimal as dec
class calc1:
'calc1 class is used for addition, subtraction only'
obj_count = 0
def __init__(self, value1, value2):
self.value1 = value1
self.value2 = value2
calc1.obj_count = calc1.obj_count + 1
def add(self):
return dec.Decimal(self.value1 + self.value2)
def sub(self):
return dec.Decimal(self.value1 - self.value2)
def __str__(self):
return str(self.add()) + " " + str(self.sub())
obj_list = []
for i in range(5):
obj_list.append(calc1(3 * i, 5.6 * i))
print(obj_list[i])输出:
0.0 %0
8.6 -2.5999999999999996447286321199499070644378662109375 17.2 -5.199999999999999289457264239899814128875732421875 25.799999999999997 -7.7999999999999971578290569595992565155029296875 34.4 -10.39999999999999857891452847979962825775146484375
发布于 2020-11-09 20:38:25
您的问题是,您正在将一个已经具有浮点精度的值传递给您的类,进而传递给Decimal类。
要避免这种情况,只需向Decimal提供您想要分配给它的数字的字符串表示形式。
from decimal import Decimal
class Calc1:
def __init__(self, val_1, val_2):
# these are now Decimal objects
self.val_1 = val_1
self.val_2 = val_2
def add(self):
# the Decimal conversion can be removed here
# since both numbers are already Decimals
return self.val_1 + self.val_2
def sub(self):
return self.val_1 - self.val_2
def __str__(self):
return str(self.add()) + " " + str(self.sub())
lst = []
for i in range(5):
i_as_dec = Decimal(i)
# Here we multiply a decimal representation of each of our numbers
# this will hand a Decimal object to the Calc1 class
lst.append(Calc1(Decimal('3') * i_as_dec, Decimal('5.6') * i_as_dec))
print(lst[i])输出:
0.0 0.0
8.6 -2.6
17.2 -5.2
25.8 -7.8
34.4 -10.4发布于 2020-11-09 20:42:44
然而,每当我运行它时,即使我在代码中包含了decimal.Decimal(),结果仍然是不舍入的。
根据its docs,这符合decimal.Decimal应该做的事情
类decimal.Decimal(value="0",context=None)根据值构造一个新的Decimal对象。(...)如果value是一个浮点数,则将二进制浮点值无损地转换为它的十进制等效值。这种转换通常需要53位或更多的精度。例如,Decimal(float('1.1'))转换为Decimal('1.100000000000000088817841970012523233890533447265625').
旁注:decimal.Decimal是类,而不是函数。
要生成人类可读的结果,我们可以对结果使用round函数或使用decimal.Decimal()函数。
除此之外,您可能决定格式化您的输出,例如使用所谓的f-strings,例如,如果我想在小数后面有4位数字:
x = 0.1 + 0.1 + 0.1
print(x) # 0.30000000000000004
print(f'{x:.4f}') # 0.3000请记住,f-string仅在python3.6和更新版本中可用,如果您必须使用旧版本,请考虑使用其他格式化方法。
https://stackoverflow.com/questions/64751583
复制相似问题