Python 当从一个变量中减去前一个变量的新值时,如何中断一段时间?
当从一个变量中减去前一个变量的新值时,如何中断一段时间 代码是:Python 当从一个变量中减去前一个变量的新值时,如何中断一段时间?,python,while-loop,break,Python,While Loop,Break,当从一个变量中减去前一个变量的新值时,如何中断一段时间 代码是: Calc = (PTO2.h - coefficients[1]) / coefficients[0] while True: NewP = IAPWS97(P=PH5, s=Calc) Calc = (NewP.h - coefficients[1]) / coefficients[0] print(NewP.h) 结果如下: 3181.2423174700475, 3125.5329929699737
Calc = (PTO2.h - coefficients[1]) / coefficients[0]
while True:
NewP = IAPWS97(P=PH5, s=Calc)
Calc = (NewP.h - coefficients[1]) / coefficients[0]
print(NewP.h)
结果如下:
3181.2423174700475, 3125.5329929699737, 3145.170908432667,
3138.216970209225, 3140.675480138904, 3139.805801319479,
3140.1133819014494, 3140.0045917261796, 3140.043069467109,
3140.029460245017, 3140.034273686281, 3140.032571219946,
3140.033173365131
这个想法是在值不再增加时停止,即3140,它应该是最终值。
此问题可通过5次或6次迭代解决。请检查这是否符合您的要求:
# Define required difference
difference = 0.1
solutions = []
# Add 1st solution or guess
# func is whatever function you are using, with the required arguments, arg.
solutions.append(func(arg))
delta = soltutions[-1]
# Check if delta is still positive and if the delta meets the requirements
while delta > 0 and delta > difference:
solutions.append(func(arg))
delta = solutions[-2] - solutions[-1]
print(f'Final result is: {solutions[-1]}')
此解决方案假定,如果变量开始变为负值,您希望完成执行。如果符号不重要,您可以在delta
中使用abs()
它的拼写是“break”,而不是“brake”,Python有一个与此名称完全相同的关键字。