Почему этот исходный код отображает только две точки? - PullRequest
0 голосов
/ 13 марта 2020

Нарисуйте 10000 точек на плоскости так, чтобы координаты x и y каждой точки находились в диапазоне [-1, 1].
Выведите координаты только тех точек, которые содержатся по кругу с радиусом r0 = 1,0.

def nextRandom(seed):
    m = 233280 # modulus
    a = 9301 # multiplier
    c = 49297 # increment
    x0 = seed # start-value
    return 2*(((a * x0 + c) % m)/m)-1 # between [-1, 1]

N = 10

x = [0]*N
y = [0]*N
p = [0]*N
x0 = 1
y0 = 0
r = 1.0

for i in range(1, N, 1):
    x[i] = nextRandom(x0)
    y[i] = nextRandom(x[i])
    p[i] = x[i] * x[i] + y[i] * y[i] 
    if(p[i]<=r*r):
        print(i, "(", "{0:.2f}, ".format(x[i]), "{0:.2f}".format(y[i]), ")")

import matplotlib.pyplot as plt
plt.scatter(x, y)
plt.show()

Выход

In [33]: runfile('C:/Users/pc/Desktop/temp.py', wdir='C:/Users/pc/Desktop/')
1 ( -0.50,  -0.62 )
2 ( -0.50,  -0.62 )
3 ( -0.50,  -0.62 )
4 ( -0.50,  -0.62 )
5 ( -0.50,  -0.62 )
6 ( -0.50,  -0.62 )
7 ( -0.50,  -0.62 )
8 ( -0.50,  -0.62 )
9 ( -0.50,  -0.62 )

enter image description here

Почему этот исходный код отображает только две точки?

Редактировать: изменил код следующим образом:

for i in range(1, N, 1):
    x[i] = nextRandom(x0)
    x0 = x[i] ##<=========================added this line
    y[i] = nextRandom(x[i])
    p[i] = x[i] * x[i] + y[i] * y[i] 
    if(p[i]<=r*r):
        print(i, "(", "{0:.2f}, ".format(x[i]), "{0:.2f}".format(y[i]), ")")

Вывод

1 ( -0.50,  -0.62 )
2 ( -0.62,  -0.63 )
3 ( -0.63,  -0.63 )
4 ( -0.63,  -0.63 )
5 ( -0.63,  -0.63 )
6 ( -0.63,  -0.63 )
7 ( -0.63,  -0.63 )
8 ( -0.63,  -0.63 )
9 ( -0.63,  -0.63 )

enter image description here

Я не вижу особых улучшений.

1 Ответ

0 голосов
/ 13 марта 2020

Похоже, проблема с предложенной схемой генерации случайных чисел. Вместо деления на m в функции nextRandom вы можете сгенерировать набор псевдослучайных целых чисел между 0 и m, затем изменить их масштаб и построить график.

# output ints!
def nextRandom(seed):
    m = 233280 # modulus
    a = 9301 # multiplier
    c = 49297 # increment
    x0 = seed # start-value
    return ((a * x0 + c) % m)

# generate (hopefully) random ints
m = 233280
# initialize integer arrays to store iterative applications
# of nextRandom. Random seed for x is 0, random seed for y is 1
rx, ry = [0], [1]
for i in range(500):
  rx.append(nextRandom(rx[-1]))
  ry.append(nextRandom(ry[-1]))

# rescale to the 2x2 square around the origin
xs = [2*x/m-1 for x in rx]
ys = [2*y/m-1 for y in ry]
# different colors based on distance to the origin
color = ['red' if x**2 + y**2 < 1 else 'blue' for x, y in zip(xs, ys)]

from matplotlib import pyplot as plt
plt.scatter(xs, ys, c=color)

Результаты выглядят следующим образом:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...