如何在NumPy数组中使用索引进行计算
我想让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)
提前谢谢你们
编辑
我想我明白了。我在len(xx)-1外面加了一个range(),这个我在上面的代码里修正了。现在我得到了正确的答案。
1 个回答
1
使用 numpy
的时候,你不需要手动一个一个地去循环。你可以用索引范围来处理数据,比如 xx[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