问题:什么时候用 trunc() 代替 int() 将浮点数转换为整数更好?

truncint函数为我尝试过的每个浮点类型输入返回相同的输出。

它们的不同之处在于int也可用于将数字字符串转换为整数。

所以我有两个问题:

1.我想知道除了字符串之外,是否有任何输入可以让truncint给出不同的输出?

2、如果不是,什么时候只用trunc把浮点数转成整数比较好?

推荐内容

解答

int and math.trunc have a somewhat similar relationship as str and repr.int委托给一个类型的__int__方法,如果没有找到__int__则回退到__trunc__方法。math.trunc直接委托给该类型的__trunc__方法,并且没有回退。与始终为object定义的__str____repr__不同,intmath.trunc都可以立即引发错误。

对于我知道的所有内置类型,__int____trunc__都在适当的地方进行了合理的定义。但是,您可以定义自己的一组测试类来查看您遇到的错误:

class A:
    def __int__(self):
        return 1

class B:
    def __trunc__(self):
        return 1

class C(): pass

math.trunc(A())math.trunc(C())都会提高TypeError: type X doesn't define __trunc__ methodint(C())将提高TypeError: int() argument must be a string, a bytes-like object or a number, not 'C'。但是,int(A())int(B())math.trunc(B())都会成功。

最终决定使用哪种方法是内涵之一。trunc本质上是类似于floor的数学运算,而int是通用转换,在更多情况下成功。

并且不要忘记operator.index__index__方法。

Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐