什么时候使用 trunc() 而不是 int() 将浮点型数字转换为整数更好?

When is it better to use trunc() instead of int() to convert floating type numbers to integers?

truncint 为我尝试过的每个浮点型输入提供相同的输出 return。

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

所以我有两个问题:

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

  2. 如果不是,什么时候只使用 trunc 将浮点型数字转换为整数更好?

int and math.trunc have a somewhat similar relationship as str and repr. int delegates to a type's __int__ method, and falls back to the __trunc__ method if __int__ is not found. math.trunc delegates to the type's __trunc__ method directly and has no fallback. Unlike __str__ and __repr__,它们总是为 object 定义,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 and the __index__ 方法。