Ask Your Question
0

Normalize vector to euclidean unit length

asked 2012-10-10 09:20:15 +0100

MvG gravatar image

I know I can compute a vector of unit length in a given direction using something like

v = some_vector_computation()
v = v/v.norm()
some_other_computation(v)

On the other hand, the most intuitive way to write this in a single line won't work:

some_other_computation(some_vector_computation().normalize())

This is because of the way normalize is defined, which is well documented and has been discussed in this question.

So I wonder, is there some other way to write the above in a single line? I'm not interested in solutions which call some_vector_computation twice, or have to name the vector, or use some lambda function, or similar hacks. I very much have a method in mind, but anything with similar complexibility and readability would be fine.

I know I could probably add my own method to the vector class at runtime, but modifying sage classes in this way doesn't exactly feel right. And I fear that using a non-standard method might make my code much harder to read, as others would expect being able to reproduce it, but won't be able to if they missed my custom method.

If there is no such method, do you agree that there should be, and that I should file a feature request on the Sage Trac?

edit retag flag offensive close merge delete

Comments

1
John Palmieri gravatar imageJohn Palmieri ( 2012-10-10 18:20:25 +0100 )edit

2 Answers

Sort by ยป oldest newest most voted
1

answered 2013-06-03 19:33:22 +0100

Eviatar Bach gravatar image

Note that as of Sage 5.7 (see trac #13393) the normalized method normalizes to unit length, normalize has been deprecated, and monic is the old functionality.

sage: v = vector([3, 2, 1])
sage: v.normalized()
(3/14*sqrt(14), 1/7*sqrt(14), 1/14*sqrt(14))
sage: v.monic()
(1, 2/3, 1/3)
edit flag offensive delete link more
1

answered 2012-10-10 23:27:37 +0100

benjaminfjones gravatar image

If you insist on a one-liner (which isn't necessarily easier to read than your original three liner in my opinion) and don't want to inject a new method or subclass Vector, you can always define your own top level normalize function and use function composition instead of chaining method calls:

def normalize(v): return v/v.norm()
some_other_computation(normalize(some_vector_computation()))
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2012-10-10 09:20:15 +0100

Seen: 3,144 times

Last updated: Jun 03 '13