I’m calculating the length of a line segment in python, but I don’t understand why one piece of code gives me zero and the other gives the right answer.
This piece of code gives me zero:
def distance(a, b):
y = b[1]-a[1]
x = b[0]-a[0]
ans=y^2+x^2
return ans^(1/2)
This one gives me the right answer:
import math as math
def distance(a, b):
y = b[1]-a[1]
x = b[0]-a[0]
ans=y*y+x*x
return math.sqrt(ans)
Thank you.
In your first snippet you have written this:
In Python the power operator is not
^, that’s the XOR-operator. The power operator in Python is**. On top of that, in Python 2.x by default the result of the division of two integers is an integer, so1/2will evaluate as0. The correct way would be this:And another thing, the function you have implemented here can be done a lot easier with
math.hypot: