在numpy数组中存储中间值

2 投票
3 回答
882 浏览
提问于 2025-04-27 13:26

我正在尝试模拟一个二维的随机漫步,方向在0到2π之间,总共走1000步。

a=np.zeros((1000,1000))

def randwalk(x,y):
    theta=2*math.pi*rd.rand() 
    x+=math.cos(theta);          
    y+=math.sin(theta);          
    return (x,y)

我该如何把所有中间的坐标存储在a里面呢?我最开始尝试用这样的方式:

for i in range(1000):
    for j in range(1000):
        a[i,j] = randwalk(x,y)

但是这样似乎根本不行。

暂无标签

3 个回答

0

你遇到了类型错误。randwalk 返回的是一个包含两个元素的元组,而你却想把它放到一个需要浮点数的数组位置上。

首先,你其实不需要一个 1000 x 1000 的数组。这样会有一百万个数据点,但你只需要 2000 个。我觉得你想要的应该是这样的:

xs = np.zeros((1000))
ys = np.zeros((1000))
x = 0
y = 0
for i in range(1000):
    xs[i], ys[i] = randwalk()

另外,应该把 randwalk 的定义改成不接收任何参数,并把 x 和 y 设为全局变量:

def randwalk():
    global x, y

现在的情况是,你在修改参数的值,但这些值并没有在每次调用时累积起来。

0

你可能想要这样的东西:

T = 1000
a = [(0,0)] * T

for i in range(1, len(a)):
    a[i] = randwalk(*a[i - 1])

这里不需要用到numpy。

1

主要的问题很明显,你想要的是一个包含1000个点的二维数组,而不是一个1000x1000的数组。举个例子,你说你想走1000步,但你的嵌套循环实际上走了1,000,000步。

import numpy as np
import matplotlib.pyplot as plt
import random as rd
import math

a=np.zeros((1000,2), dtype=np.float)

def randwalk(x,y):
    theta=2*math.pi*rd.random() 
    x+=math.cos(theta);          
    y+=math.sin(theta);          
    return (x,y)

x, y = 0., 0.
for i in range(1000):
    x, y = randwalk(x,y)
    a[i,:] = x, y

plt.figure()
plt.plot(a[:,0], a[:,1])
plt.show()

enter image description here

撰写回答