Question

this is my first visit so pls dont hate me, if this post sucks. Yes, I already asked google and looked around here, too.

So: I need to normalize 3D vectors. Got a function that takes the vector and returns a new normalized vector. No Problem so far - just when their length is 0 i get (NaN, NaN, NaN). What does Vector normalization usually do to Vectors with length of 0? Is it ok to just check the length for 0 and return (0.0, 0.0, 0.0)?

Thx

Was it helpful?

Solution

Vector normalization is a partial function—it's just not defined on the null vector. How you want to model that undefinedness is a design decision, and you've got a lot of options in Scala. The most obvious is to just do the math with Double and go with the NaNs that result, so that (NaN, NaN, NaN) represents undefinedness. Another approach would be to use a proper partial function:

val normalize: PartialFunction[Point, Point] = {
  case p if p.magnitude > 0 => ...
}

Now you'll get a MatchError exception if you try to normalize the null vector.

You could also use an ordinary method (or function) that throws an exception if the null vector is given as input. This gives you more control over the exception message, etc., but also means you lose some of the additional convenience offered by PartialFunction in Scala.

You could also use a method that returns an Option[Point]:

def normalize(p: Point): Option[Point] = if (p.magnitude == 0.0) None else Some(
  ...
)

And so on—the point is that there are lots of ways you can model undefinedness, and picking the best one for your program will be a matter of balancing performance, correctness, convenience for your use cases, etc.

Lastly—as you say, you could write a special case for normalize that maps the null vector to itself, but note that this will break the invariant that the output is always a unit vector. Again, maybe that's just fine, but it's something to watch out for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top