【发布时间】:2021-04-19 11:11:31
【问题描述】:
我需要制定一个算法来执行具有 2 个 while 循环的任务。 我将解释我想要实现的目标。我需要根据 h 值的长度进行循环。那么循环应该与 f.ex 一起迈出一大步。 3 或 2 或 4,while 或 for 循环中的项目应检查条件或方程式。我需要检查何时或哪个项目的值给方程中的 n 赋予零值。 当 n 值达到零时,我需要使用 0.1 执行更小的步骤。因为我需要更精确。没有必要在开始时以小步长开始循环,它会减慢执行时间,并且知道 item 的精确小值会给出零到 n 方程的值是很有趣的。当 n 方程接近零值时也是如此。
举例说明: 循环 1 开始并迈出大步。
h = 50
st = 10
loop 1 starts
0 , 3, 6, 9, 12, 15, 18, 21, 24 ………………… #<-------- steps from h value
25.0 , 22.0 , 19.0, 16.0, 13.0, 10.0, 7.0, 4.0, 1.0 ………………… #<-------- calculate values from n equation
If n <= 2 or n>= -2:
|_____ loop 2 starts with:
24.0, 23.9 , 23.8, 23.7, 23.6, …………….. #<-------- small steps iterate with hj = 24+st
0.4, 0.3 , 0.1, 0.0, -1.0, …………….. #<-------- calculate values from n equation
Calculate n values from n equation
M = 2 + n
If (n <= 0 or n>= -1) and M==2 : #<-------- If statement is fullfilled then return some values and quit loop 2 and loop 1.
Return n, itemstep from loop 2, M
Elif (n <= 0 or n>= -1) and M!=2:
Quit loop 2 and 1 #<-------- If statement is not fullfilled then quit loop 2 and loop 1.
n >= -1 的原因,因为我们可以从 50 开始逐步下降到 0,并且 n 值也可以是负数。 我试图用下面的代码弄清楚它,但它似乎不起作用,这是在while或for循环中生成此类代码的一种方法。
M = 2 #<---------- to check conditions
j = 0
st = 10
h = 50 #<---------- to iterate over length h
n = h/2 - j #<---------- to calculate n values (n equation)
result =[]
while j <=h: #<---------- loop 1
n = h/2 - j
if n <= 3 or n >= -3: #<---------- if this is satisified then start loop2
print(n)
i=j
while i < 10+st: #<---------- loop 2
n = h/2-i
M = 2+n
if (n <= 0 or n>= -1) and M==2:
result.append(n, i, M) #<---------- return values
i = 70+j #<---------- stop loop 2 and loop 1
j = h+70
elif (n <= 0 or n>= -1) and M!=2: #<---------- if this is not satisified then quit loop2 and loop 1
i = 70+j #<---------- stop loop 2 and loop 1
j = h+70
i +=0.1
j += i
j += 3
【问题讨论】:
-
目标是使 n 为 0 吗?直觉上,你的许多“或”逻辑应该是“和”
-
是的,这就是得到0的关键。
-
如果你只需要一次大步模式,然后移动到小步,你不必嵌套循环。应该是一会儿接着一会儿。您介意修改 psdudo 代码以使用“和”,这将有助于其他人了解您在做什么
-
如果您希望最小化函数
lambda h, j: h / 2 - j的值,也许 docs.scipy.org/doc/scipy/reference/generated/… 会有所帮助... -
@AKX,找到最小化确实很有趣,我的任务是在 excel 中寻找目标。
标签: python python-3.x performance for-loop while-loop