简体   繁体   中英

How can I generate three random numbers in python as a vector components fulfiling the magnitude of the vector

I was wondering how I can generate random numbers in python for Fx, Fy, and Fz in the equation F = sqrt (Fx^2+ Fy^2+Fz^2), where F eg, is [10, 20, 30, 40] and I would also like to store the values of Fx, Fy, and Fz in three different lists.

Thank you in advance.

This describes points on a sphere, we can use this information to compute random points on that sphere:

import random
import math

def random_F(r):
    phi=random.uniform(0,2*math.pi)
    theta = random.uniform(0,2*math.pi)
    Fx = r*math.cos(phi)*math.sin(theta)
    Fy = r*math.sin(phi)*math.sin(theta)
    Fz = r*math.cos(theta)
    return Fx,Fy,Fz

Fx=[0]*4
Fy=[0]*4
Fz=[0]*4

for i in range(4):
    Fx[i],Fy[i],Fz[i] = random_F(10+10*i)

# checking if correct
for i in range(4):
    print(math.sqrt(Fx[i]**2+Fy[i]**2+Fz[i]**2))

output:

10.0
20.0
30.0
40.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM