How to compute the cross product of two 3D vectors in C++

1 Answer

0 votes
// How do you compute the cross product of two 3D vectors? Write the formula explicitly.

#include <iostream>
#include <array>

// ------------------------------------------------------------
// Compute the cross product of two 3D vectors a × b.
// The cross product produces a new vector that is perpendicular
// to both a and b.
//
// Explicit formula for a = (ax, ay, az) and b = (bx, by, bz):
//
//     a × b = ( ay*bz - az*by,
//               az*bx - ax*bz,
//               ax*by - ay*bx )
//
// This matches the determinant expansion:
//
// |  i    j    k  |
// | ax   ay   az |
// | bx   by   bz |
// ------------------------------------------------------------
std::array<double, 3> cross(const std::array<double, 3>& a,
                            const std::array<double, 3>& b) {
    return {
        a[1]*b[2] - a[2]*b[1],   // x-component
        a[2]*b[0] - a[0]*b[2],   // y-component
        a[0]*b[1] - a[1]*b[0]    // z-component
    };
}

int main() {
    // 3D vectors // A 3D vector has exactly three components:
    std::array<double, 3> a = {1, 0, 2};
    std::array<double, 3> b = {3, 1, 0};

    // Compute cross product
    auto c = cross(a, b);

    std::cout << "Cross product: ["
              << c[0] << ", " << c[1] << ", " << c[2] << "]\n";
}



/*
run:

Cross product: [-2, 6, 1]

*/

 



answered 3 hours ago by avibootz
...