sqrt: ValueError: math domain error

匿名 (未验证) 提交于 2019-12-03 01:20:02

问题:

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

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 

回答1:

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.

Your fixed code:

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


回答2:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!