sqrt:ValueError:数学域错误

Joh*_*ohn 4 python math

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

这是我的代码:

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
Run Code Online (Sandbox Code Playgroud)

orl*_*rlp 11

您的问题是Python中的取幂是否使用a ** b而不是a ^ b(^按位XOR),这会导致final为负值,从而导致域错误.

你的固定代码:

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


Sve*_*ach 6

Python中的幂函数**不是^(这是位xor).所以使用x3**2