本文介绍了为什么这个源代码只绘制了两个点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在平面上绘制 10,000 个点,使每个点的 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 )

为什么这个源代码只绘制了两个点?

Why is this source code plotting only two points?

修改代码如下:

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 )

我没有看到太大的改进.

I am not seeing much improvement.

推荐答案

看起来像是提议的随机数生成方案的问题.在nextRandom函数中不用除以m,你可以在0m之间生成一堆伪随机整数,然后重新缩放和绘图.

Looks like an issue with the proposed random number generation scheme. Instead of dividing by m in the nextRandom function, you can generate a bunch of pseudorandom integers between 0 and m, then rescale and plot.

# 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)

结果如下:

这篇关于为什么这个源代码只绘制了两个点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 23:00