【发布时间】:2021-02-21 22:29:18
【问题描述】:
我正在尝试通过继承浮点类并重载与其关联的运算符,在 Python 中创建一个自定义浮点类“Float”。我正在重载与类关联的算术运算符,以获得decimal.Decimal类的精度进行算术计算,同时保持float类的性能远优于decimal.Decimal类。
这样,当我需要显示人类可读的输出时,我不需要使用 round() 函数或字符串格式。
这是我的代码,仅重载了加法运算符:
class Float(float): #custom float class
def Float(self,value): #Constructor like method
self.value = value
def count_decimal_places(float_num): #Counts decimal places for rounding
if type(float_num) == int:
return 0
return len(str(float_num).split('.')[1])
def __add__(self, other): #rounds results to the higher number of decimal places
return round(self.value +other.value, max(self.count_decimal_places(self.value), self.count_decimal_places(other.value))
fo = Float()
fo.Float(3.6)
fo2 = Float()
fo2.Float(5.6)
print(fo + fo2)
当我直接在类中使用构造函数为“value”属性赋值时,这不起作用。
class Float(float):
def init(self,value):
self.value = value
def count_decimal_places(float_num):
if type(float_num) == int:
return 0
return len(str(float_num).split('.')[1])
def __add__(self, other):
return round(self.value +other.value, max(self.count_decimal_places(self.value), self.count_decimal_places(other.value))
fo = Float(3.6)
fo2 = Float(5.6)
print(fo + fo2)
它产生了一个语法错误。这就是为什么我在第一个代码中使用了类似构造函数的方法。
init 方法也存在于 Python 中的类 float 并显示在 print(dir(float)) 中,但我无法确定它的作用,所以我没有使用类的预定义构造函数浮动。
【问题讨论】:
-
请显示导致错误的minimal reproducible example。
def __init__上面的行中的错误是最可能的原因。 -
"我正在重载类关联的算术运算符,以获得小数的精度。小数类进行算术计算,同时保持浮点类的性能远优于十进制。十进制类。”为什么你相信你能做到?看起来你根本没有这样做,你只是在四舍五入(即使这样我怀疑性能会比
decimal.Decimal更好,它是用 C 实现的,但也许......但它肯定不是相同的精度,它仍然有相同的精确浮点问题 -
我编辑了我的帖子并添加了我使用 def init 时的代码。
-
juanpa.arrivillaga 我不确定我是否理解。我正在尝试调整小数位数以进行舍入并重载算术运算符,以便 4.0 - 2.7 将 1.3 存储在变量中,而不是 1.29999998。
-
另外,您的
count_decimal_places方法没有意义,您检查type是否为int,但您总是将其传递给float...
标签: python python-3.x constructor floating-point precision