Python 2D Numpy数组初学者的烦恼
我的问题是如何处理数组,因为每个元素都是一个由2个值组成的元组 具体地说,问题是生成200步(但对于测试来说是2步)的随机二维行走,最大距离,然后每个阶段100步(尝试2步),并在距离前一阶段原点的最大距离处开始每个阶段 我可以成功生成随机步数数组,让它们返回最终位置(x,y)值,并计算它们与每次行走原点的距离: 这些函数中定义了:Python 2D Numpy数组初学者的烦恼,python,arrays,numpy,multidimensional-array,Python,Arrays,Numpy,Multidimensional Array,我的问题是如何处理数组,因为每个元素都是一个由2个值组成的元组 具体地说,问题是生成200步(但对于测试来说是2步)的随机二维行走,最大距离,然后每个阶段100步(尝试2步),并在距离前一阶段原点的最大距离处开始每个阶段 我可以成功生成随机步数数组,让它们返回最终位置(x,y)值,并计算它们与每次行走原点的距离: 这些函数中定义了: #............................................................getPositionInteger de
#............................................................getPositionInteger
def getPosInt(description) :
"""Asks the user to enter a positive integer"""
askAgain = False
while askAgain == False:
try:
posInt = eval(raw_input("\n %s : " %description))
assert 0 < posInt , "Not a positive integer"
assert type(posInt) == int , "Not a positive integer"
askAgain = True
except :
print "Input failed, not a positive integer"
return posInt
#...............................................................initialPosition
def initialPosition() :
"""Initial position of walker at the start of a random walk"""
return (0.0, 0.0)
#......................................................................distance
def distance(posA, posB) :
"""Distance between two positions"""
xi = posA[0] ; yi = posA[1]
xf = posB[0] ; yf = posB[1]
return np.sqrt((xf-xi)**2+(yf-yi)**2)
#..................................................................getPositions
def getPositions(start, nSteps, maxStep):
xArray = maxStep * np.random.random(nSteps+1)* np.cos(2.0 * np.pi * random.random())
yArray = maxStep * np.random.random(nSteps+1)* np.sin(2.0 * np.pi * random.random())
xArray[0] = start[0]
yArray[0] = start[-1]
xArray = np.cumsum(xArray)
yArray = np.cumsum(yArray)
return (xArray[-1], yArray[-1])
你会发现我在制作(x,y)样式的数组时遇到了麻烦,其中[0]应该是[0.0,0.0],并且它会打印两次,此外,它不会更改到最终位置
我真的很感激你能提供的帮助、建议或推荐。
谢谢
-Sid显然还有其他几件事是错误的,但首先将
walks
数组定义为walks=np.zero((NUM_walks,2),dtype=np.float)
,然后看看您自己能想出什么。
import numpy as np
import matplotlib.pylab as plt
import random
import time
MAX_STEP_SIZE = 0.90 # maximum size of a single step [m]
random.seed(12345)
#..........................................................................main
def main ():
''''''
print "RANDOM WALK IN STAGES IN TWO DIMENSIONS"
userdata = getDetails()
print "\nPlease wait while random walks are generated and analyzed..."
NUM_STAGES = userdata[0]
NUM_WALKS = userdata[1]
NUM_STEPS = userdata[2]
stageStart = initialPosition()
for stage in np.arange(NUM_STAGES):
walks = np.zeros((NUM_WALKS, NUM_WALKS), dtype=np.ndarray)
for walk in walks:
walk = getPositions(stageStart, NUM_STEPS, MAX_STEP_SIZE)
print walk
print walks