【发布时间】:2021-10-17 00:44:54
【问题描述】:
我对 python 很陌生。我想编写一个函数,它可以在每 30 秒内生成每个圆坐标。 到目前为止我的代码是这样的:
import sched, time
import numpy as np
scheduler = sched.scheduler(time.time, time.sleep)
def coords():
theta = np.linspace(0, 2*np.pi, 1000)
radius = .5
x = radius * np.sin( theta )
y = radius * np.cos( theta )
z = 4.2
pos = []
for i in range (0, 1000):
pos = (x[i], y[i], z)
i+=1
#print(pos)
e1 = scheduler.enter(1, 1, coords)
e2 = scheduler.enter(30, 1, coords)
我不知道我做错了什么,请帮忙! 谢谢。
编辑以提供更多代码:
import time
import numpy as np
def distance(a, b):
distance = np.sqrt((a[0]-b[0])*(a[0]-b[0])+(a[1]-b[1])*
(a[1]- b[1])+(a[2]-b[2])*(a[2]-b[2]))
return distance
def coords():
theta = np.linspace(0, 2*np.pi, 1000)
radius = .5
x = radius * np.sin( theta )
y = radius * np.cos( theta )
z = 4.2
pos = []
for i in range (0, 1000):
pos = (x[i], y[i], z)
return pos
def main():
goal = np.array([3.6528202764153976, -7.055446756786874524,
8.52021764])
current = coords()
print(current)
while True:
dis = distance(goal,current)
print(dis)
time.sleep(3)
if __name__ == "__main__":
main()
【问题讨论】:
-
它工作正常, (0.0, 0.5, 4.2) 9.438863921224838 每 3 秒打印一次。你想要 coords() 返回所有生成位置的列表(不仅仅是最后一个)吗?
-
而在主()要电流以获得更接近目标像这样?:[0.0,0.5,4.2] 9.438863921224838 [0.0031447166580338753,0.4999901106593416,4.2] 9.437639450965634 [0.006289308919370529,0.49996044302856274,4.2] 9.436400082070367 [ 0.009433652392233545, 0.4999109982812366, 4.2] 9.435145857703839
-
嗨@LazyBumQ,是的,我希望 coords() 每 3 秒返回一次所有生成位置(不仅仅是最后一个)的列表,以便 main() 可以计算与目标的距离。但是 coords() 只返回一个位置!有什么建议吗?
-
更改了我的答案,这应该可以。询问您是否需要更多解释。
标签: python-3.x for-loop time coordinates sched