Tag Archives: saving

A few weeks back, someone asked me a question that, as someone who has worked with computer graphics quite a bit, I should have instantly known the answer to: how to compute a dot product of two vectors. Instead, I floundered for an answer and tried just about every way but the correct way I could conceive of because the correct way ‘didn’t look right’ to me. If you’ve ever spelled a word and then thought, ‘that doesn’t look right’ even though you have spelled it correctly, you’ll know what I mean.

In my defense, I had been running low on sleep and energy for a few weeks at that point due to working on a proposal. So not only was I tired, I was cold on writing code. Worse, I hadn’t written a line of graphics-related code in months.

These are really just excuses though. Eventually I slogged through to the correct answer, but I felt like I had completely misrepresented myself to this person.

So, without further ado, here is an example of how to compute a dot product between two vectors in C++:

There are a dozen other methods that should be added to this class as well, like a cross-product, conversion to a unit vector, or a method for determining the angle between this vector and another, but it occurred to me that there are plenty of C++ libraries out there that already do this. However, is there one for Swift? I’m not sure – there are the beginnings of a Vector2D in the Swift Programming Language Guide, but it is clearly not finished.

I decided I’d mirror the functionality of the above C++ class in a Swift class in a playground as a start in the direction of creating a reusable vector class: