-3

I have been tasked with making a vector magnitude function in C++ as part of a maths library for a class project, however I am unsure how to go about this, if someone could recommend some pages to read and or give me some help that would be great

Edit: My C++ knowledge isn't that great, I'm looking for pages to help me learn how to do functions for vectors

Steven Cowie
  • 21
  • 1
  • 1
  • 2
  • Hint: Pythagoras. Oh and it might be good to provide a magnitude square function also, as `std::sqrt` is not the fastest function and it's often not needed. – George Nov 13 '17 at 14:41
  • 1
    It is not clear at all what information is missing to achieve your goal: C++ Knowledge? You don't define magnitude. You mean euclidean length? How does your vector data structure look like? – lars Nov 13 '17 at 14:43
  • If the is a collective project, you must agree with other members on the data representations. –  Nov 13 '17 at 15:20

2 Answers2

4

A quick google comes up with

magnitudes

As this is a class project I'll let you read the link rather than giving full details here.

You may want to read up on using vectors, for instance here.

Personally I prefer to use C++ standard algorithms where possible. You can do this sort of thing quickly and efficiently with std::accumulate.

#include <iostream>
#include <vector>
#include <numeric>
#include <string>
#include <functional>

int main()
{
    std::vector<double> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    double ssq = std::accumulate(v.begin(), v.end(),
                                    0.0,
                                    /* add here */);

    std::cout << "ssq: " << ssq << '\n';
}

The line marked /* add here */ is where you need to add an operator that takes the current running sum of squares and the next value to add to it, and returns the new running sum of squares.

Alternatively, you could just write a for loop

double ssq = 0.0;
std::vector<double> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (auto e : v)
{
    // calculate sum of squares here
}
Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
1

Take a revisit to GCSE maths:

c² = a² + b²

double magnitude = sqrt((Vector.x*Vector.x) + (Vector.y*Vector.y));