如何创建一个循环,重复以下但每次从 a 中减去 0.1?

How do I create a loop repeating the following but each time deducting 0.1 from a?

如何创建一个循环,重复以下但每次从 a=10 中减去 0.1?它应该重复 100 次然后停止。 谢谢!

for i in x:
    yt = (a - 0.1)* i
    MSE = np.square(np.subtract(y,yt)).mean()

您可以改用 while 循环,如下所示:

a = 10
while a > 0:
    yt = (a-0.1)
    MSE = np.square(np.subtract(y,yt)).mean()
    a -= 0.1

这样,如果 a == 0 循环停止并且 yt 不会变为 0。如果这就是您所要求的。由于精度问题,重复的 -0.1 通常会导致舍入错误并可能产生不需要的结果。因此我建议使用这样的东西:

a = 100
while a > 0:
    yt = (a/10-0.1)
    MSE = np.square(np.subtract(y,yt)).mean()
    a -= 1

或者在最新评论之后:使用在每个循环索引中迭代比较的临时值:

import numpy as np
a = 10
y = 5.423           #example value
tmp_MSE = np.infty  #the first calculated MSE is always smaller then infty
tmp_a = a           #if no modified a results in a better MSE, a itself is closest 
for i in range(100):
    yt = a-0.1*(i+1)
    MSE = np.square(np.subtract(y,yt)).mean()
    if MSE < tmp_MSE: #new MSE comparison
        tmp_MSE = MSE #tmp files are updated
        tmp_a = yt

print("nearest value of a and MSE:",tmp_a,tmp_MSE)