Python初学者,为什么数学回归了NaN?

Python初学者,为什么数学回归了NaN?,python,math,Python,Math,我已经为我所在的班级准备了一些代码,但我不明白为什么要返回NaN 我以前从未使用过数学模块 代码如下: import random as rndm import math # helper function to start and restart the game def get_guesses(low, high): global guesses #x = low - high + 1 #guesses = math.log(x, 2) guesses = m

我已经为我所在的班级准备了一些代码,但我不明白为什么要返回NaN

我以前从未使用过数学模块

代码如下:

import random as rndm
import math
# helper function to start and restart the game
def get_guesses(low, high):
    global guesses
    #x = low - high + 1
    #guesses = math.log(x, 2)
    guesses = math.log(low - high + 1, 2)
    return guesses

def new_game():
    global secret_number, guesses, first
    if first:
        first = False
        secret_number = rndm.randrange(0, 100)
        guesses = get_guesses(0, 99)
    print guesses
    print secret_number
你通过了
low=0
high=99
,因此等式小于零:
0-99+1=-98

负数的对数在中,这是
数学
模块不支持的(它只处理实数)

因此,您得到的是一个值错误:

>>> math.log(0 - 99 + 1, 2)
Traceback (most recent call last):
  File "<pyshell#51>", line 1, in <module>
    math.log(0 - 99 + 1, 2)
ValueError: math domain error

但我怀疑这是否真的是你想要的;)

猜测值实际上不应该既是全局值又是返回值。下定决心好观点!!!非常感谢。(:经验法则:如果你使用的是global关键字,那么你的程序结构是错误的。你在计算负数的对数。虽然我认为这会抛出ValueError而不是返回NaN。Ricky,我正在学习。我知道我不应该使用它们,但我仍在努力掌握大部分概念!!我这么做不是为了这么做!哈哈,当我不从高位减去任何东西并加上一个时,我怎么会得到一个负数?@acollection\u我想我已经解释过那部分了?
low
是0,
high
是99,而你在做
low-high+1
就是
0-99+1=-98
。你可能是想从
high
中减去
low
high-low+1=99-0+1=100
。是的。我现在明白了。对不起,这是一个漫长的夜晚,哈哈哈。我把数字颠倒过来,当我意识到我做了什么时,我回来发现你实际上告诉了我问题是什么,哈哈哈。谢谢你,先生!!现在我更了解数学模块了!所以也谢谢你(:不客气,很高兴我能帮上忙。)请记住,如果你的问题解决了,请将问题标记为已解决。
>>> math.log(0 - 99 + 1, 2)
Traceback (most recent call last):
  File "<pyshell#51>", line 1, in <module>
    math.log(0 - 99 + 1, 2)
ValueError: math domain error
>>> import cmath
>>> cmath.log(0 - 99 + 1, 2)
(6.614709844115209+4.532360141827194j)