Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在具有一定距离的外圆内生成随机点_Python_Math_Random - Fatal编程技术网

Python 在具有一定距离的外圆内生成随机点

Python 在具有一定距离的外圆内生成随机点,python,math,random,Python,Math,Random,我目前真的被我的一些代码卡住了,我似乎找不到问题所在。以下是我试图做的: 我有一个大的外圆,我想在其中显示较小的点。这些点应随机分布,但不应重叠,因此它们之间的距离应最小 我尝试的是首先随机生成一个点,检查它是否在外圆中,如果在外圆中,则将其附加到点位置的最终列表中。然后创建另一个点,如果在圆中进行检查,则应检查该点与最终列表中其他点之间的距离是否最小 但是,我的代码似乎有一些问题,因为每当我将所需的距离设置为大于1时,它都不会运行。我已经改变了很多事情,但我不能让它工作 有人知道问题出在哪里吗

我目前真的被我的一些代码卡住了,我似乎找不到问题所在。以下是我试图做的: 我有一个大的外圆,我想在其中显示较小的点。这些点应随机分布,但不应重叠,因此它们之间的距离应最小

我尝试的是首先随机生成一个点,检查它是否在外圆中,如果在外圆中,则将其附加到点位置的最终列表中。然后创建另一个点,如果在圆中进行检查,则应检查该点与最终列表中其他点之间的距离是否最小

但是,我的代码似乎有一些问题,因为每当我将所需的距离设置为大于1时,它都不会运行。我已经改变了很多事情,但我不能让它工作

有人知道问题出在哪里吗

以下是我一直在尝试的:

import random
import numpy as np
import math

#Variables
radiusOC = 57
size_obj = 7
required_dist = 5
no_stimuli = 3


def CreatePos(radiusOC, size_obj, required_dist, no_stimuli):
    final_list = []
    def GenRandPos(radiusOC,size_obj):
        """
        Takes the radius of the outer circle and generates random dots within this radius. Then checks if the the dots are located 
        within the outer circle.
        """
        while True:
            xPos = random.randint(-radiusOC,radiusOC)
            yPos = random.randint(-radiusOC,radiusOC)
        
            # check if in Circle 
            on_circle = (xPos- 0)**2 + (yPos-0)**2
            if (radiusOC-size_obj)**2 >= on_circle:
                print("Still in circle",on_circle, xPos, yPos )
                position = [xPos, yPos]
                break
            else:
                print("Not in circle",on_circle, xPos, yPos )
                continue
                
        return position


    def CheckSurrounding(position, final_list, required_dist): 
        """
        Takes dot positions that are in the visual field, the list of positions, and the distances dots are required to have from each other. 
        It is checked if there are dots close by or not.  
        """
        X1 = position[0]
        Y1 = position[1]
        dist_list = []
        for elem in final_list:
            for i in elem: 
                X2 = elem[0]
                Y2 = elem[1]
                dist = math.sqrt((X1-X2)**2 + (Y1-Y2)**2)
                dist_list.append(dist)
                
        if all(dist_list) >= required_dist: 
            return position
            
        else:
            return None

    # append the first dot to the list
    position = GenRandPos(radiusOC, size_obj)
    final_list.append(position)

    # now append the rest of the dots if they have a certain distance to each other
    while len(final_list) < no_stimuli: 
        position = GenRandPos(radiusOC, size_obj)

        if CheckSurrounding(position, final_list, required_dist)  != None: 
            position = CheckSurrounding(position, final_list, required_dist)
            final_list.append(position)

        else: 
            continue
    
    return final_list


´´´
随机导入
将numpy作为np导入
输入数学
#变数
半径OC=57
尺寸_obj=7
所需距离=5
无刺激=3
def CreatePos(半径、大小、所需距离、无刺激):
最终清单=[]
def GenRandPos(半径,尺寸):
"""
取外圆的半径,并在此半径内生成随机点。然后检查这些点是否定位
在外圆内。
"""
尽管如此:
xPos=random.randint(-radiusOC,radiusOC)
yPos=random.randint(-radiusOC,radiusOC)
#检查是否在圆圈内
圆上=(xPos-0)**2+(yPos-0)**2
如果(半径OC-size\u obj)**2>=在圆上:
打印(“仍在圆圈内”,在圆圈、XPO、YPO上)
位置=[XPO,YPO]
打破
其他:
打印(“不在圆圈内”,在圆圈、XPO、YPO上)
持续
返回位置
def检查环境(位置、最终列表、所需区域):
"""
获取视野中的点位置、位置列表以及点之间所需的距离。
检查附近是否有点。
"""
X1=位置[0]
Y1=位置[1]
dist_list=[]
对于最终清单中的要素:
对于元素中的i:
X2=元素[0]
Y2=元素[1]
距离=数学sqrt((X1-X2)**2+(Y1-Y2)**2)
dist_list.append(dist)
如果所有(地区列表)>=所需地区:
返回位置
其他:
一无所获
#将第一个点附加到列表中
位置=GenRandPos(半径、尺寸)
最终列表。附加(位置)
#现在,如果其余的点彼此之间有一定的距离,则附加它们
而len(最终列表)<无刺激:
位置=GenRandPos(半径、尺寸)
如果检查周围(位置、最终列表、所需距离)!=无:
位置=检查周围(位置、最终列表、所需距离)
最终列表。附加(位置)
其他:
持续
返回最终用户列表
´´´
在行中

if all(dist_list) >= required_dist:
all(dist_list)
将为
True
False
,在数值上等于1或0。如果
required\u dist
大于1,则该不等式将永远无法满足。我想这是你的本意

if all(dist_list >= required_dist):
但这不起作用,因为您无法将列表
dist\u list
与数字
required\u dist
进行比较。要修复它,请将
dist\u list
转换为numpy数组:

if np.all(np.array(dist_list) >= required_dist):
顺便说一下,您选择的随机点将始终具有整数坐标,因为您使用的是
random.randint()
,我不确定这是否是有意的

使用numpy数组可以提高整个代码的效率。例如:

import numpy as np

def CreatePos(radiusOC, size_obj, required_dist, no_stimuli):
    final_list = []

    def GenRandPos(radiusOC, size_obj):
        """
        Takes the radius of the outer circle and generates 
        random dots within this radius. Then checks if the dots are 
        located within the outer circle.
        """

        while True:
            position = (2 * np.random.random(2) - 1) * radiusOC
            # check if in Circle
            if (radiusOC - size_obj)**2 >= (position**2).sum():
                return position

    def CheckSurrounding(position, final_list, required_dist):
        """
        Takes dot positions that are in the visual field, 
        the list of positions, and the distances dots are 
        required to have from each other. 
        It is checked if there are dots close by or not.  
        """

        final_arr = np.array(final_list)
        dist = ((np.array(final_list) - position)**2).sum(axis=1)
        if np.all(np.array(dist) >= required_dist**2):
            return position

    # append the first dot to the list
    position = GenRandPos(radiusOC, size_obj)
    final_list.append(position)

    # now append the rest of the dots if they have a certain distance to each other
    while len(final_list) < no_stimuli:
        position = GenRandPos(radiusOC, size_obj)
        if CheckSurrounding(position, final_list, required_dist) is not None:
            final_list.append(position)

    return final_list
绘制结果点:

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(7,7))
ax = fig.add_subplot(111)
ax.set_aspect("equal")
plt.scatter(f[:, 0], f[:, 1])
plt.show()
这使得:

我会在最后的
while
循环中添加一个条件,这样如果在多次尝试后找不到新的点,它就会中断。否则,它可能会无限期地运行。

在该行中

if all(dist_list) >= required_dist:
all(dist_list)
将为
True
False
,在数值上等于1或0。如果
required\u dist
大于1,则该不等式将永远无法满足。我想这是你的本意

if all(dist_list >= required_dist):
但这不起作用,因为您无法将列表
dist\u list
与数字
required\u dist
进行比较。要修复它,请将
dist\u list
转换为numpy数组:

if np.all(np.array(dist_list) >= required_dist):
顺便说一下,您选择的随机点将始终具有整数坐标,因为您使用的是
random.randint()
,我不确定这是否是有意的

使用numpy数组可以提高整个代码的效率。例如:

import numpy as np

def CreatePos(radiusOC, size_obj, required_dist, no_stimuli):
    final_list = []

    def GenRandPos(radiusOC, size_obj):
        """
        Takes the radius of the outer circle and generates 
        random dots within this radius. Then checks if the dots are 
        located within the outer circle.
        """

        while True:
            position = (2 * np.random.random(2) - 1) * radiusOC
            # check if in Circle
            if (radiusOC - size_obj)**2 >= (position**2).sum():
                return position

    def CheckSurrounding(position, final_list, required_dist):
        """
        Takes dot positions that are in the visual field, 
        the list of positions, and the distances dots are 
        required to have from each other. 
        It is checked if there are dots close by or not.  
        """

        final_arr = np.array(final_list)
        dist = ((np.array(final_list) - position)**2).sum(axis=1)
        if np.all(np.array(dist) >= required_dist**2):
            return position

    # append the first dot to the list
    position = GenRandPos(radiusOC, size_obj)
    final_list.append(position)

    # now append the rest of the dots if they have a certain distance to each other
    while len(final_list) < no_stimuli:
        position = GenRandPos(radiusOC, size_obj)
        if CheckSurrounding(position, final_list, required_dist) is not None:
            final_list.append(position)

    return final_list
绘制结果点:

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(7,7))
ax = fig.add_subplot(111)
ax.set_aspect("equal")
plt.scatter(f[:, 0], f[:, 1])
plt.show()
这使得:


我会在最后的
while
循环中添加一个条件,这样如果在多次尝试后找不到新的点,它就会中断。否则,它可能会无限期地运行。

您需要找到一种方法来估计给定距离的最大点数。这可以从圆形填料问题中推断出来。我会评论,如果我有一个简单的检查做

将numpy导入为np
从matplotlib导入pyplot作为plt
从scipy.spatial.distance导入cdist
定义圆中的随机点(点数=1000,R=1,最小距离=0.2):
断言最小距离