简单的随机向量函数不止一次返回相同的方向 [英] Simple random vector function returns same direction more than once

查看:55
本文介绍了简单的随机向量函数不止一次返回相同的方向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我制作了这个简单的函数来使用 pygame 返回一个大小为 1 的随机向量,基本上是一个随机向量,然后被归一化(给出一个方向).但是,当我运行调用此函数的 for 循环时,有些方向是相同的,如果不只是翻转 180 或 smth.我迭代了 3 次,只是因为如果它不能做 3 个随机向量,我不能相信它可以做数百个......

So I made this simple function to return a random vector of magnitude 1 using pygame, basically a random vector that is then normalized (giving a direction). However, when I run a for loop calling this function, some of the directions are the same, if not just flipped 180 or smth. I'm iterating 3 times, just because if it can't do 3 random vectors, I can't trust it to do hundreds...

import random
import math
from pygame import Vector2

def random_direction():
    vector = Vector2(random.uniform(-10, 10), random.uniform(-10, 10))
    if vector.length() == 0:
        return vector
    else:
        return Vector2.normalize(vector)

for i in range(3):
    v = random_direction()
    print(v)
    print(math.degrees(math.atan2(v.y,v.x)))

输出示例:

[-0.481089, 0.876672]
118.75655978063934
[0.524372, 0.851489]
58.374037634092204
[-0.504321, 0.863516]
120.2862923019005

如您所见,第二个和第三个角度相同,只是翻转了.我尝试过其他 PRNG,但没有对它们进行标准化,但似乎没有任何改变.

As you can see, the second and third are the same angle, just flipped. I've tried other PRNG's, not normalizing them, but nothing seems to change it.

推荐答案

在一个类中为对象实现了该函数,我想给出随机方向并在 for 循环内创建 n 个对象.因此,将其作为对象属性与其他属性一起实现,而不是连续 3 次查找随机向量即可修复它...

Implemented the function inside a class for objects which I wanted to give that random direction and created n objects inside a for-loop. So implementing it as an object attribute alongside others instead of finding a random vector 3 times in a row fixes it...

这篇关于简单的随机向量函数不止一次返回相同的方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆