0

I am a newbie in python. I am stuck by finding the length of a path in 2d. I have no idea what I'm doing wrong. Please help!

import math
vector1 = v1
vector2 = v2
def length (v):

    """ Length of a vector in 2-space.

    Params: v (2-tuple) vector in 2-space
    Returns: (float) length
    """
    v = sqrt(v1**2 + v2**2)
    return v



def dist (P,Q):

    """ Distance in 2-space.

    Params: 
        P (2-tuple): a point in 2-space
        Q (2-tuple): another point in 2-space
    Returns: (float) dist (P,Q)
    """
    dist = [(Q - P) **2]
    dist = math.sqrt(sum(dist))
    return dist


P = [p0, p1]
Q = [q0, q1]
def pathLength2d (pt):

    """Length of a 2-dimensional path.

    Standard length as measured by a ruler.

    Params: pt (list of 2-tuples): path in 2-space

    Returns: (float) length of this path
    """
    pt = math.hypot(q0 - p0, q1 -p1)
    return pt

print (pathLength2d ([(0,0), (1,1)]))
Stop harming Monica
  • 12,141
  • 1
  • 36
  • 56
Amber Flynn
  • 45
  • 1
  • 3
  • Please format your post correctly. The formatting is all over the place. Please read the help centre to improve your post, otherwise it will be closed. Unless you improve it, you will get low quality answers, and votes to remove it. – techydesigner Sep 30 '16 at 02:22

2 Answers2

0

Yes, please fix your formatting, shift everything by four spaces.

But I believe your first method is:

   def length(v):
       """ Length of a vector in 2-space.
       Params: v (2-tuple) vector in 2-space
       Returns: (float) length
       """ 
       v = sqrt(v1**2 + v2**2)
       return v

That method doesn't know what v1 and v2 are, you need to define them like this:

def length(v):
    """ Length of a vector in 2-space.
    Params: v (2-tuple) vector in 2-space
    Returns: (float) length
    """ 
    v1 = v(0)
    v2 = v(1)
    v = math.sqrt(v1**2 + v2**2)
    return v

you also need to use math.sqrt

For the distance function, you can't subtract two tuples like that. you'll need something as follows:

def dist(P, Q):
    """ Distance in 2-space.
    Params: 
        P (2-tuple): a point in 2-space
        Q (2-tuple): another point in 2-space
    Returns: (float) dist (P,Q)
    """
    dist = math.sqrt((P[0] - Q[0])**2 + (P[1]-Q[1])**2)
    return dist
Tony
  • 31
  • 4
0
def euc_distance (x_1,y_1,x_2,y_2):
    x = (x_1 - x_2)**2
    y = (y_1 - y_2)**2

    distance = ( x + y)**0.5

    return distance
Kate Kiatsiri
  • 63
  • 2
  • 7
  • 2
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you’ve made. – Ismael Padilla Jan 22 '20 at 23:07