# Normalize vector to euclidean unit length

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 close merge delete

1

Sort by » oldest newest most voted

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)

more

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()))

more