如何使用while循环非顺序迭代并动态更新范围边界求解最优d值
解决方案
你需要的是区间收缩搜索逻辑,无需遍历全部w值,每次根据返回的d值动态缩小区间范围,直到区间内无更多符合步长的可选值即可得到最小abs(d)的唯一解,全程不需要设置固定阈值。
可运行完整代码
import numpy as np # 保留原有计算函数 def Calculations(a, b): A = a * b - a B = a * b - b d = A - B return(A, B, d, a, b) # 存储每个l对应的最优结果 A_opt = [] B_opt = [] d_opt = [] l_opt = [] w_opt = [] # 全局参数配置 length = np.arange(60, 62.5, 0.5) w_step = 0.5 init_w_lower = 50 init_w_upper = 70.5 for l in length: current_lower = init_w_lower current_upper = init_w_upper min_abs_d = float('inf') best_result = None # 终止条件:区间内无符合步长的可选w值 while current_upper - current_lower > w_step: # 生成当前区间内所有可选w值并随机选一个 available_w = np.arange(current_lower, current_upper, w_step) selected_w = np.random.choice(available_w) # 计算当前值 res = Calculations(l, selected_w) current_d = res[2] current_abs_d = abs(current_d) # 更新最优记录 if current_abs_d < min_abs_d: min_abs_d = current_abs_d best_result = res # 收缩区间 if current_d < 0: current_upper = selected_w else: current_lower = selected_w # 最后对比区间边界的两个候选值,避免随机选点漏最优解 for end_w in [current_lower, current_upper - w_step]: res = Calculations(l, end_w) current_abs_d = abs(res[2]) if current_abs_d < min_abs_d: min_abs_d = current_abs_d best_result = res # 存入最优结果 A_opt.append(best_result[0]) B_opt.append(best_result[1]) d_opt.append(best_result[2]) l_opt.append(best_result[3]) w_opt.append(best_result[4]) # 输出结果 print("最优A值:", A_opt, "\n") print("最优B值:", B_opt, "\n") print("最优d值:", d_opt, "\n") print("对应l值:", l_opt, "\n") print("对应w值:", w_opt, "\n")
逻辑说明
- 完全符合你的区间更新规则:d为负则将当前选中的w设为新的搜索上限,d为正则设为新的搜索下限
- 无固定阈值终止条件:当上下限差值小于等于步长时,区间内已无更多符合步长的可选w值,自动结束当前l的搜索
- 每个l值仅保留唯一最优结果:搜索过程中全程记录最小abs(d)对应的所有返回值,最后再对比区间边界的两个候选值,确保不会漏掉最优解
- 所有关联值同步存储:最优结果对应的A、B、d、l、w都会分别存入对应列表,方便后续调用
补充说明:你定义的d化简后实际为d = w - l,因此理论上最优解为w和l相等时abs(d)=0,运行代码可以验证输出的w值会和对应的l值完全一致,符合预期。
内容的提问来源于stack exchange,提问作者greenrabbit
相关产品推荐
相关产品推荐

