【问题标题】:What value for x will cause math.isfinite(x) to return False? [duplicate]x 的什么值会导致 math.isfinite(x) 返回 False? [复制]
【发布时间】:2018-08-09 12:40:10
【问题描述】:

在 Python 中,如果传递的参数是有限数,math.isfinite 函数将返回 True。我想知道将返回False 的表达式或方程(生成无限值的方程),而不是'NAN'。传递一个数字除以 0 会报错。

【问题讨论】:

标签: python-3.x


【解决方案1】:

在提出此类问题之前,您应该始终阅读文档。只需在 REPL 中使用 help(math.isfinite) 即可告诉您哪些值返回 False。

Help on built-in function isfinite in module math:

isfinite(...)
    isfinite(x) -> bool

    Return True if x is neither an infinity nor a NaN, and False otherwise.

就像 Martijn Peters 提到的,float('inf')float('-inf') 都将产生无限值。在 Python 3.5+ 中,您还可以使用 math.inf 作为生成这些值的一种方式。

【讨论】:

  • 我想知道一个有效的等式或表达式,它会生成无限值并导致此函数返回 false。
【解决方案2】:

如果你想创造无限的价值,你应该使用

float('inf') # positive infinity 

下面这些值都是False

import math
math.isfinite(float('inf'))
math.isfinite(float('-inf'))
math.isfinite(float('nan'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 2015-06-02
    • 1970-01-01
    相关资源
    最近更新 更多