Norming a Vector

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

Norming a Vector

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

Hi,

Code: Select all
import math

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

def length(u):
    return math.sqrt(length_squared(u))
   
def scale_by_scalar(u, scalar):
    return [a * scalar for a in u]

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

print norm([100, 6])


The answer of this program is: [0.9982048454657786, 0.05989229072794672]

However, if I were to set the print norm function as the following: print norm([100, 0]) it would give me: [1.0, 0.0]

Why does it give me those floating point values if 100 * (1 / sqrt(100^2)) is 1 and 6 * (1 / sqrt(6^2)) is 1? I also thought sum adds up these two values which would give 2?
Indiiyana
 
Posts: 10
Joined: Tue Nov 26, 2013 1:55 am

Re: Norming a Vector

Postby stranac » Sat Jan 25, 2014 8:19 pm

Your code is calculating
Code: Select all
[100 / sqrt(100**2 + 6**2), 6 / sqrt(100**2 + 6**2)]
You are talking about
Code: Select all
100 * (1 / sqrt(100**2)) + 6 * (1 / sqrt(6**2))
Friendship is magic!

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

Re: Norming a Vector

Postby Indiiyana » Sun Jan 26, 2014 12:24 am

I see.

My logic is completely wrong then, I don't suppose you could tell me what happens step by step with this program?

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


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests