def aitken_iteration(functions, limit, n, x0):
    x0_list = [x0] * len(functions)  # 保存初值
    x1_list = [func(x0_list[j]) for j, func in enumerate(functions)]  # 保存x1
    x_list = [x0] * len(functions)  # 迭代数据
    flag_list = [0] * len(functions)  # 标记是否迭代完成
    funcname = '\t'.join([func.__name__ for func in functions])  # 函数名作表头
    x0_str = '\t'.join([str(x0)] * len(functions))  # x0的值作为表头第二行
    data = f"n\t{funcname}
0\t{x0_str}
"  # 表头
    x1_str = '\t'.join([str(x1_list[j]) for j in range(len(functions))])  # 第一步迭代的数据
    data += f"1\t{x1_str}
"  # 增加表格第一步迭代对应的行
    for i in range(2, n + 1):
        if all(flag == 1 for flag in flag_list):  # 所有迭代都完成则不继续进行迭代
            break
        row = f"{i}\t"  # 当前行
        for j, func in enumerate(functions):
            if flag_list[j] == 1:
                row += "\t"  # 迭代完成,不显示
                continue
            try:
                x2 = func(x1_list[j])
                p = x0_list[j] - (x1_list[j] - x0_list[j]) ** 2 / (x2 - 2 * x1_list[j] + x0_list[j])
                if abs(p - x_list[j]) < limit:  # 数据收敛
                    row += f"{p}\t"
                    flag_list[j] = 1
                    continue
                x0_list[j] = x1_list[j]
                x1_list[j] = x2
                x_list[j] = p
            except OverflowError:
                row += "溢出\t"  # 数据溢出异常
                flag_list[j] = 1  # 标记迭代完成
                continue  # 继续计算其他函数
            row += f"{p}\t"
        row += "\n"
        data += row
    with open('aitken_iteration_results.txt', 'w') as fileptr:
        fileptr.write(data)

该代码首先使用列表 x0_list 保存 x0 的初始值,并使用 x1_list 保存第一步迭代结果。然后,使用 flag_list 标记每个函数是否已经迭代完成。在函数开头,添加代码生成包含 x0 值的表头第二行,并将其添加到 data 中。最后,将计算结果输出到文本文件 aitken_iteration_results.txt 中。

通过以上修改,代码可以输出包含 x0 值的表头第二行,使结果更清晰易懂。

Aitken 迭代法实现及结果输出

原文地址: https://www.cveoy.top/t/topic/lJjn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录