Making a vector of specific length with random numbers

Viewed 100

I tried writing a program that would give me the i,j and k components of a vector of a specified magnitude.

import random
import math

while True:
    a = random.uniform(0,1000)
    b = random.uniform(0,1000)
    c = random.uniform(0,1000)
    d = 69.420
    
    if math.sqrt(a**2 + b**2 + c**2) == d:
        print(a,b,c)
        break

But it seems that this program might take literally forever to give me an output.

What would faster or possible solution be?

#Update

import random
import math


while True:
    a2 = random.uniform(1,1000)
    b2 = random.uniform(1,1000)
    c2 = random.uniform(1,1000)
    d = 69.420

    d2 = a2 + b2 + c2
    
    a2 *= d/d2
    b2 *= d/d2
    c2 *= d/d2
    
    a = math.sqrt(a2)
    b = math.sqrt(b2)
    c = math.sqrt(c2)
    
    if math.sqrt(a**2 + b**2 + c**2) == d:
        print(a,b,c)
        break

As per suggested, but still taking a very long time to compute

1 Answers

Get three random numbers a2, b2, and c2. Those are your random squares. Add them up to get d2. You want the sum of the squares to be d squared, so multiply a2, b2, and c2 by d*d/d2. These are your new squares that add up to d squared. Now assign the square roots of a2, b2, and c2 to a, b, and c. Does that make sense?

Avoid dividing by zero. If d2 happens to be zero, just start over.

Related