我如何创建一个循环重复以下内容,但每次从a中扣除0.1 ?



如何创建一个循环,重复以下内容,但每次从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)

最新更新