sqrt:ValueError:数学域错误 [英] sqrt: ValueError: math domain error

查看:118
本文介绍了sqrt:ValueError:数学域错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我的代码:

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

推荐答案

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

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

您的固定代码:

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

这篇关于sqrt:ValueError:数学域错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆