简体   繁体   English

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

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

How do I create a loop repeating the following but each time deducting 0.1 more from a=10 ?如何创建一个循环重复以下内容,但每次从a=10中减去 0.1 ? It should repeat a 100 times and then stop.它应该重复 100 次然后停止。 Thanks!谢谢!

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

You could use a while loop instead, like the following:您可以改用 while 循环,如下所示:

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

That way, if a == 0 the loop stops and yt won't become 0. If that is what you are asking for.这样,如果 a == 0 循环停止并且 yt 不会变为 0。如果那是您所要求的。 Due to accurancy problems, often a repeated -0.1 will result in rounding errors and could create unwanted results.由于精度问题,通常重复的 -0.1 会导致舍入错误,并可能产生不需要的结果。 Thus I recommand using something like this:因此我建议使用这样的东西:

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

Alternatively after the newest comment: Using temporary values which get compared iteratively every loop index:或者在最新评论之后:使用每个循环索引迭代比较的临时值:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何阻止代码重复相同的计算,而是每次都进行随机计算 - How do I stop the code from repeating the same calculation and instead have a random calculation each time 从每列中减去中位数 - Deducting the median from each column 如何在python中创建一个函数,每次在while循环中累积 - How do I create a function in python that accumilates each time in a while loop 如何获得这个for循环来创建一个dataframe,而不是每次循环时都创建一个新的? - How do I get this for loop to create one dataframe, instead of creating a new one each time it loops? 创建一个以0.1个间隔增加的重复元素数组 - Create an array of repeating elements that increase by 0.1 intervals 如何在 Jupyter Notebook 中循环以下代码,而不是为每个输入文件重复相同的步骤? - How to Loop the following CODE in Jupyter Notebook instead of repeating same steps for each input files? 如何从下图中创建邻接矩阵? - How do I create an adjacency matrix from the following graph? 在Python中,如何在每次循环时创建一个新变量,然后将它们全部发送给要处理的函数? - In Python, how do I create a new variable each time a loop goes around, and then send them all to a function to be processed? 如何在Numpy中向量化以下循环? - How do I vectorize the following loop in Numpy? 我如何更改绘图,使点的宽度也按[-0.1:0.1]变化 - how do i change my plot so the dots also vary by [-0.1:0.1] in the width
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM