0

I'm trying to develop a C++ function to normalize a 4 element vector. I think that the vector math inside of the function is correct, but I'm not quite sure how to get the normalized vector elements out of the function (without using global variables).

//  NORMALIZATION FUNCTION //

double normalizeThis(double q0,double q1,double q2,double q3){

    double mag; // unnormalized vector magnitude variable

    mag = pow((pow(q0,2)+pow(q1,2)+pow(q2,2)+pow(q3,2)),0.5); // calculating magnitude 
 
    q0 = q0/mag; q1 = q1/mag; q2 = q2/mag; q3 = q3/mag; // normalization!!

    return q0; q1; q2; q3;

}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • 2
    Pass the variables by reference? – Algirdas Preidžius May 31 '21 at 13:54
  • 2
    Use a structure or [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) to return? – MikeCAT May 31 '21 at 13:55
  • There's a good answer on this post - https://stackoverflow.com/questions/321068/returning-multiple-values-from-a-c-function. IMHO, C++17's tuple is best in this context. – Uri Raz May 31 '21 at 14:04
  • 1
    don't use `pow(x, 0.5)` to calculate the square root. Do like this instead: `sqrt(q0*q0 + q1*q1 + q2*q2 + q3*q3);`. Shorter, cleaner, easier to read, more correct and faster – phuclv May 31 '21 at 14:45

1 Answers1

0

Using structured binding, it would look like this...

#include <tuple>
#include <iostream>

using namespace std;

std::tuple<double, double, double, double> normalizeThis(double q0, double q1, double q2, double q3) {
    double mag; // unnormalized vector magnitude variable

    mag = pow((pow(q0, 2) + pow(q1, 2) + pow(q2, 2) + pow(q3, 2)), 0.5); // calculating magnitude 

    q0 /= mag; q1 /= mag; q2 /= mag; q3 /= mag; // normalization!!

    return std::make_tuple(q0, q1, q2, q3);
}

int main() {
    auto [a, b, c, d] = normalizeThis(1., 2., 3., 4.);

    std::cout << a << ',' << b << ',' << c << ',' << d << std::endl;
}
Uri Raz
  • 435
  • 1
  • 3
  • 15
  • C++ 17 allows returning multiple variables, see https://www.fluentcpp.com/2018/06/19/3-simple-c17-features-that-will-make-your-code-simpler/ – Alejandro Caro May 31 '21 at 15:12