2017-06-20 107 views
1

所以我想制作一个程序,说明函数2^n -15 = xt中的n的解是什么,其中n是正整数,xt是平方数。但是,这并不工作:为什么sqrt(xt)无法正常工作? ValueError:数学领域错误

from math import sqrt 
n = 0 
def is_square(x): 
    answer = sqrt(x) 
    return answer.is_integer() 

while True: 
    n += 1 
    xt = 2^n - 15 
    if is_square(xt): 
     print(xt) 

错误这样说:当你的参数sqrt是负数可能发生

Traceback (most recent call last): 
    File "C:/Users/NemPl/Desktop/Python/Python programi/M/P #1.py", line 9, in <module> 
    if is_square(xt): 
    File "C:/Users/NemPl/Desktop/Python/Python programi/M/P #1.py", line 4, in is_square 
    answer = sqrt(x) 
ValueError: math domain error 
+2

我怀疑'2^n'确实是你想要的 – polku

+2

(1)插入符号''不计算功率,但是按位异或。要计算权力使用'**'。 (2)你创建了一个无限循环。 Python会继续下去,直到遇到错误。在你的情况下,你早点击,当'2^n-15'马上消失时。为了解决这个问题,定义一个标准来结束循环:'if n> 1000:break'。 – Boldewyn

回答

3

简答题:你的目标是计算一个负数的平方根。

如果再加上一个print(xt)语句的程序:

while True: 
    n += 1 
    xt = 2^n - 15 
    print(xt) 
    if is_square(xt): 
     print(xt)

我们看到,被查询的第一要素,是:

-16 

虽然有复杂数字,代表方负数的根,math.sqrt(..)适用于浮点数,因此“实数”的子集。现在对于实数,负数的平方根是而不是定义的。

最后不是^不计算功率,人们可以通过使用2 ** n(或1 << n在这种情况下)计算功率。脱字号^是按位或

5

此错误。

math.sqrt函数不能计算负数的平方。

可以使用cmath lib中负数:

import cmath 
print (cmath.sqrt(-2)) 
>>> 1.4142135623730951j 
2

math.sqrt显然不喜欢负数,这将导致一个复杂的结果。从documentation

These functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for complex numbers. The distinction between functions which support complex numbers and those which don’t is made since most users do not want to learn quite as much mathematics as required to understand complex numbers. Receiving an exception instead of a complex result allows earlier detection of the unexpected complex number used as a parameter, so that the programmer can determine how and why it was generated in the first place.

使用cmath.sqrt()cmath如果需要复杂的结果也是如此。