I've written a program that generates pairs of integer 3d vectors and finds the angle between them.

I save the answer (the angle) as a rational multiple of pi:

    m = newRandomVector(3);
n = newRandomVector(3);
str_m = vector_to_string(m);
str_n = vector_to_string(n);
double mag1 = m.norm();
double mag2 = n.norm();
double prod = mag1 * mag2;
double cos = m.dot(n) / (mag1 * mag2);
double angle = acos (cos) * 180.0; /// PI;
sprintf(answer, "%lf/%lf * PI ", m.dot(n), prod);

However, generating random vectors crates almost exclusively float magnitudes.

How can I generate a 3D vector with an integer magnitude?

  • 1
    $\begingroup$ You could try to find solutions to the Diophantine equation $a^2 + b^2 + c^2 = d^2$. That way, $(a, b, c)$ has integer norm. $\endgroup$ – Sean Roberson Jul 19 '17 at 20:16
  • $\begingroup$ Well... if you allow one of the entries to be zero you could simply use Pythagorean Triples, e.g. $\|(0,3,4)\|=5$. After a short google search on related terms, this leads us to Pythagorean Quadruples. E.g. $\|(2,3,6)\|=7$. There is a list of all possible primitive pythagorean quadruples with all positive entries with all entries less than 30. To create more such vectors, just permute the first three terms and apply sign changes. $\endgroup$ – JMoravitz Jul 19 '17 at 20:16
  • $\begingroup$ could you do scalar multiplication to normalize vectors to integer magnitude something like "n=( int(n.norm())+1 )/ n.norm() * n" using whatever is the correct syntax for scalar multiplication. $\endgroup$ – WW1 Jul 19 '17 at 20:26

You seem to have two concerns. One is immediate, all solutions to $a^2 + b^2 + c^2 = d^2 $ with $\gcd(a,b,c,d) = 1$ are given by a formula probably known to Euler, but associated with V. A. Lebesgue. It is not possible to have $d$ even unless the others are also even, making the gcd 2 or larger. We take $a,d$ as the odd numbers, with $$ a = m^2 + n^2 - p^2 - q^2, $$ $$ b = 2 (mq+np), $$ $$ c = 2 (nq - mp), $$ $$ d = m^2 + n^2 + p^2 + q^2. $$

I can add that we can find all solutions to $a^2 + b^2 + c^2 = 3 d^2.$ With two such vectors, the ratio involved in the cosine of the angle between them would be rational (not the angle over pi, that is quite rare). See Niven's book, Irrational Numbers.

  • $\begingroup$ Thank you Will! I'm terrible at math. Does your solution allow m, n, p, and q to just be random integers? $\endgroup$ – maddie Jul 19 '17 at 21:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.