Set Length of Vector

This is the place for queries that don't fit in any of the other categories.

Set Length of Vector

Postby Indiiyana » Sat Jan 25, 2014 4:17 am

Hi,

Code: Select all
import math

u = [1, 2]
v = [3, 4]

def length_squared(u):
    return sum([a ** 2 for a in u])

def length(u):
    return math.sqrt(length_squared(u))

def sub(u, v):
    return [a - b for a, b in zip(u, v)]

def scale_by_scalar(u, scalar):
    return [a * scalar for a in u]

def dist(u, v):
    return length(sub(v, u))

def dist_squared(u, v):
    return length_squared(sub(v, u))

def setlength(u, 1):
    return scale_by_scalar(u, 1 / length(u))

def norm(u):
    return setlength(u, 1)

print norm([100, 0])    # gives [1, 0]
print dist(u, v)         # 2.82842712475
print dist_squared(u, v) # 8


I get the following error at def setlength(u, 1);, the error is Expected:).

I was following this tutorial: http://noobtuts.com/python/vector and if you look at the section "Setting the Length of a Vector" it has the code written out as I have. What's wrong?

Thanks.
Indiiyana
 
Posts: 10
Joined: Tue Nov 26, 2013 1:55 am

Re: Set Length of Vector

Postby micseydel » Sat Jan 25, 2014 4:21 am

That tutorial disappointingly used the lowercase version of L, not 1. It's unfortunately because single letter variable names like that are discouraged specifically because of that (although they're also often not descriptive enough).
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1506
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: Set Length of Vector

Postby Indiiyana » Sat Jan 25, 2014 3:00 pm

So you're saying it shouldn't be setlength but it should be setLength? I changed it to that but the same error occurs.
Indiiyana
 
Posts: 10
Joined: Tue Nov 26, 2013 1:55 am

Re: Set Length of Vector

Postby stranac » Sat Jan 25, 2014 3:22 pm

No, it should be the letter l, not the digit 1.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1246
Joined: Thu Feb 07, 2013 3:42 pm

Re: Set Length of Vector

Postby Indiiyana » Sat Jan 25, 2014 6:31 pm

Haha, of course.

My mistake, thanks.
Indiiyana
 
Posts: 10
Joined: Tue Nov 26, 2013 1:55 am


Return to General Coding Help

Who is online

Users browsing this forum: Hissing Cockroach, metulburr, pegasus and 7 guests