Python sqrt:ValueError:数学域错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4735448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:15:45  来源:igfitidea点击:

sqrt: ValueError: math domain error

pythonmath

提问by John

I'm facing a problem with "distance ValueError: math domain error" when using sqrtfunction in python.

在 python 中distance ValueError: math domain error使用sqrt函数时,我遇到了“ ”的问题。

Here is my code:

这是我的代码:

from math import sqrt

def distance(x1,y1,x2,y2):
    x3 = x2-x1
    xFinal = x3^2
    y3 = y2-y1
    yFinal = y3^2
    final = xFinal + yFinal
    d = sqrt(final)
    return d

回答by Sven Marnach

The power function in Python is **, not ^(which is bit-wise xor). So use x3**2etc.

Python 中的幂函数是**, not ^(按位异或)。所以使用x3**2等。

回答by orlp

Your issue is that exponentiation in Python is done using a ** band not a ^ b(^is bitwise XOR) which causes final to be a negative value, which causes a domain error.

您的问题是 Python 中的求幂是使用a ** b而不是a ^ b^按位异或)完成的,这导致 final 为负值,从而导致域错误。

Your fixed code:

您的固定代码:

def distance(x1, y1, x2, y2):
     return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** .5 # to the .5th power equals sqrt