distance formula in python bug
Question: 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.


Answer: In your first snippet you have written this:

    
    
    ans^(1/2)
    

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, so `1/2` will evaluate
as `0`. The correct way would be this:

    
    
    ans ** 0.5
    

And another thing, the function you have implemented here can be done a lot
easier with
[**`math.hypot`**](http://docs.python.org/library/math.html#math.hypot):

    
    
    import math
    
    def distance(a, b):
        return math.hypot(b[0] - a[0], b[1] - a[1])
    

