Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

python 3.x - Making a vector of specific length with random numbers

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

question from:https://stackoverflow.com/questions/65868066/making-a-vector-of-specific-length-with-random-numbers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...