简体   繁体   中英

How to generate a random vector between two vectors?

Let's say I've got two real-valued vectors:

vec1 = np.array([a, b, c])
vec2 = np.array([x, y, z])

What is a good way to generate a random vector on the line between the two vectors? So the random vector would have elements from the intervals a thru x, b thru y, and c thru z, respectively. Here's what I've got so far, but I'm wondering if there is a better way.

vec3 = np.array([np.random.uniform(vec1[i], vec2[i]) for i in range(len(vec1))])

Edit: I realized (thanks to the answer below) that this solution only finds a vector that lies in the box generated with the two vectors at opposite corners, rather than finding a vector on the line between the two vectors.

import random
vec3 = vec1 + random.uniform(0, 1) * (vec2 - vec1)

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