当从一个变量中减去前一个变量的新值时,如何中断一段时间?

2024-10-03 06:20:41 发布

您现在位置:Python中文网/ 问答频道 /正文

当从一个变量中减去前一个变量的新值时,如何中断一段时间

代码是:

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次迭代来解决


Tags: 代码truecalcprintwhile新值coefficientsnewp
1条回答
网友
1楼 · 发布于 2024-10-03 06:20:41

请检查这是否符合您的要求:

# 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()

相关问题 更多 >