2017-06-20 6 views
1

だから、関数2でnの解は何かを示すプログラムを作りたいと思います。^ n -15 = xtここで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) 

エラーは、この氏は述べています:

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)キャレット'^'は力を計算するのではなく、ビットごとにXORを計算します。力を計算するには '**'を使います。 (2)あなたは無限ループを作りました。 Pythonはエラーが発生するまで続行します。あなたのケースでは、 '2^n-15'がすぐに負になったときに、早く1つを打ちます。これを修正するには、ループを終了するための基準を定義します:if n> 1000:break'。 – Boldewyn

答えて

3

短答の平方根を計算することを目指しています。負の数です。我々はプログラムにprint(xt)文を追加する場合

:平方表し複雑数字がある

-16 

が:

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

我々が照会され、最初の要素が、あることを確認負の数の根であるmath.sqrt(..)は浮動小数点で働くので、 ""のサブセットです。実数の場合、負数の平方根はではなく、と定義されています。 ^は電源を計算しない

最後に、一方が2 ** n(又はこの場合1 << n)を使用して電力を計算することができないこと。キャレット^はビット単位またはです。

5

sqrtにあなたの引数が負の数であるときに、このエラーが発生する可能性があります。

math.sqrt関数は、負の数の2乗を計算することができません。

あなたが負の数のcmathのlibを使用することができます。

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

math.sqrt明らかに複雑な結果につながる負の数が好きではありません。 cmathから

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()あなたにも複雑な結果が必要な場合:documentationから。

関連する問題