所以我希望 perimeterpoints 函数能够工作,但我不确定如何运行数组的索引。我认为我的数组的 len 可以工作,但它说“in”对象不可迭代。因此,如果我有 10 个点,则会产生 0 到 9 的索引。
import math as m
import numpy as np
def ball(numpoints):
rr = 5. #radius of the ball
xx = np.linspace(-5,5,numpoints) #x coordinates
yy = np.array([m.sqrt(rr**2 - xxi**2) for xxi in xx]) #y coordinates
perimeterpoints = np.array([m.sqrt((xx[i+1]-xx[i])**2+(yy[i+1]-yy[i])**2) for i in range(len(xx)-1)])
perimeter = sum(perimeterpoints)
return(perimeter)
提前致谢
编辑
我想我明白了。我将 range() 放在 len(xx)-1 周围,我在上面的代码中修复了它。我得到了正确的答案
最佳答案
使用numpy
,您不需要显式迭代。您可以使用索引范围,例如xx[1:]
对应于使用 i+1
进行索引。 xx[:-1]
,最后一个。
def ball(numpts):
rr = 5
xx = np.linspace(-5,5,numpts)
yy = np.sqrt(rr**2-xx**2)
perimeterpoints = np.sqrt((xx[1:]-xx[:-1])**2+(yy[1:]-yy[:-1])**2)
perimeter = np.sum(perimeterpoints)
return perimeter
关于python - 如何使用 numpy 数组中的索引进行计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22263059/