mercredi 21 juillet 2021

While loop crashes inconsistently when generating random numbers with constraint

  1. Start with a vector, vector0

  2. Initialize a while loop that generates another random vector, vector1

  3. Use the dot product to calculate the angle between them

  4. If the angle theta between vector0 and vector1 is too large, keep re-making vector1 until it's small enough

It looks something like this:

# initialize the angle
theta = 0
# the first vector:
vector0 = [x0, y0, z0]
# initialize while loop:
while theta <= 0 or theta > np.pi/8:
    # create the second vector using random numbers
    x1 = random.uniform(-maxlen, maxlen)
    y1 = random.uniform(-maxlen, maxlen)
    z1 = random.uniform(-maxlen, maxlen)
    vector1 = [x1, y1, z1]
    # find the angle between the two vectors. The loop will start again if it is too large.
    theta = np.arccos(np.dot(vector0, vector1) / np.linalg.norm(vector0)*np.linalg.norm(vector1)

This process is nested within two other loops - not especially large ones, only 5 step & 100 step. A simple enough process, I thought.

Here is my problem: this while loop crashes about 70% of the time. Just gives up. But some of the time, it works perfectly!

It's easy to kill it and re-initialize but sometimes I'm doing this ten times over to get the code to run through successfully, which is becoming unbearable.

Am I doing something daft that is causing this? Perhaps there's a bug that sometimes triggers in my code, or I've made a mathematical error? Maybe there is a more memory/CPU-efficient way to achieve this outcome? Or do I just need to use a more powerful machine?




Aucun commentaire:

Enregistrer un commentaire