Does the standard library have a function equivalent to the following?
function norm_normalize(v, p = 2)
n = norm(v,p)
return n, v/n
If not, is there a reason why such a function does not exist?
And finally, if the function does not exist but you think that it should exist, what should the name be? The name
norm_normalize() is modeled after functions like
sincos(), but I think it’s a bit too wordy. Another option would be
normunit(), which follows a similar idea and is shorter but which is also more unclear.
I don’t know if it exists. But what is the purpose of this function? It seems trivial enough that I would write it out inline, or define my own local function.
I have a similar feeling about
reim, I don’t really see the point of it. Perhaps it’s very commonly used?
sincos is different, since it does something highly non-trivial.
But what is the purpose of this function?
Convenience. It allows you to merge two to three lines into one and avoid introducing some temporary variables. This may sound trivial, but often these things appear in quite complicated mathematical algorithms where squeezing out every bit of conciseness really helps. Also, note that
LinearAlgebra already has a
normalize() function which is about as trivial as
How do you make it three lines?
Anyway, I’m afraid I don’t know of such a function.
(I’m a bit skeptical to
v the result of some computations (e.g. a matvec
A*x) which you do not want to repeat.
norm_normalize() would allow you to reduce
v = A*x
n = norm(v)
v /= n
n,v = norm_normalize(A*x)
Seems too trivial to merit it’s own name. It’s just
x./norm(x), so I’m used to either writing that, or, if I need to pass it along somewhere, making an anonymous function.
I don’t mind it, it just seems like something that could be trimmed away. I see it has a companion,
normalize! which does slightly more.
It’s a question, what is the threshold for something to be non-trivial enough or used enough that it is worthwhile. Anyway,
normalize and this proposed new function won’t live in Base, so no big deal.
If I looked at the code for __normalize, there is more to it.
OK, good, then I guess it’s worthwhile.
normalize! turns out to be a bit more involved than expected, perhaps the proposed function is a bit more useful than I first thought.
I am on the fence about this; it is occasionally useful but also quite easy to implement when needed, so I would tend to agree with @DNF here. Also,
a = norm(v)
v /= a
is not much more complicated — I don’t really mind naming interim values (
v = A*x), which can actually make the code cleaner.
As pointed out by @mzaffalon,
normalize! does have a clever trick to fix a numerical issue. But the solution could be just exposing that, eg with
a = norm(v, p)
v2 = normalize_with(v, a)
etc, as it may be useful in other contexts.