具有两个条件的散点图随机数(图看起来像一个模糊的圆圈,里面有一个方孔)

Scatter plot random numbers with two conditions (plot will look like a fuzzy circle with a square hole inside)

我是 python 的新用户编程,需要一些帮助才能完成一项练习。 在我为 x 和 y 生成 2000 个介于 -10 和 10 之间的随机数之前,我需要确保不满足这两个要求的 x 和 y 已经出来: np.sqrt(x^2 + y^2) < 10 当 x 和 y 的绝对值 > 5 时。 我如何在绘图中插入这两个条件?

条件:

np.sqrt(x**2 + y**2) < 10
abs(x),abs(y) > 5

我是这样开始的:

import numpy as np
import matplotlib.pyplot as plt
N=2000
x = np.random.uniform(-10,10,N)
y = np.random.uniform(-10,10,N)

a = np.zeros(np.size(x), dtype=bool)
b = np.sqrt(x**2+y**2)

for i in range(np.size(x)):
    if (b[i] < 10):
        a[i] = True
x = x[a]
y = y[a]

plt.plot(x,y, "b o")
plt.show()

非常感谢您!

这是上面编辑的代码,但我仍然需要满足 x 和 y 大于 5 和 -5 的条件

伪代码为

var maxpoints = 2000
var ptx[maxpoints]
var pty[maxpoints]

for (num = 0; num < maxpoints; num++) {  # 

    do {

        trialx = np.random.uniform(-10,10,N) # create a new x
        trialy = np.random.uniform(-10,10,N) # create a new y

    } while (! ((math.sqrt(trialx**2 + trialy**2) < 10) &&
                (math.abs(trialx) > 5 && math.abs(trialy) > 5)))

    ptx[num] = trialx        
    pty[num] = trialy

}

基本上继续内部 while 循环,直到发现下一个满足限制的 x 和 y ...创建圆的限制自然会进行平方根 (x^2 + y^2) 而不是square(x^2 + y^2) ... @Jan 请澄清这一点并更新您的问题

update 我自学了一些 python 将上面的代码翻译成带有图片的工作代码

from array import array
import numpy as np
import matplotlib.pyplot as plt

circle_radius = 10

maxpoints = 2000
ptx = np.zeros(maxpoints)
pty = np.zeros(maxpoints)

seedval = circle_radius + 1

for num in range(0,maxpoints):

    trialx = seedval
    trialy = seedval

    while (not (((np.sqrt(trialx*trialx + trialy*trialy) < circle_radius)) and
                (np.abs(trialx) > 5 and np.abs(trialy) > 5))) :

        trialx = np.random.uniform(-circle_radius,circle_radius) # create a new x
        trialy = np.random.uniform(-circle_radius,circle_radius) # create a new y

        print "current trial ", trialx, trialy

    ptx[num] = trialx        
    pty[num] = trialy

    print num, trialx, trialy


plt.plot(ptx, pty, 'ro')
plt.show()

以上将生成此图

import numpy as np
import matplotlib.pyplot as plt
N=2000
x = np.random.uniform(-10,10,N)
y = np.random.uniform(-10,10,N)

a = np.zeros(np.size(x), dtype=bool)
b = np.sqrt(x**2+y**2)

for i in range(np.size(x)):
    if (max(abs(x[i]), abs(y[i]))>5) & (b[i] < 10):
        a[i] = True
    else:
        a[i] = False
x = x[a]
y = y[a]

plt.plot(x,y, "b o")
plt.show()

should look like this!!!

谢谢大家!我发现错误