You need to enable JavaScript to run this app. 实现bisection method的C代码收敛参数α计算错误问题求解
优惠活动
大模型
产品
解决方案
定价
更多

实现bisection method的C代码收敛参数α计算错误问题求解

双分法方程求解C代码的收敛参数计算问题

问题说明

在编写求解方程的双分法C代码时,遇到收敛参数计算故障,多次调整计算逻辑后始终被判定结果不正确。目前对给定公式的理解存在偏差,反复修改仍无法得到正确结果,需要对应的解决方案。

  • 任务要求:实现基础双分法求解方程,同时按照公式计算收敛参数 α = |Xₙ₊₁ - Xₙ| / |Xₙ - Xₙ₋₁|
  • 公式说明:该公式为俄文任务的谷歌翻译结果,其中n对应收敛阶数,术语表述可能存在偏差
  • 当前计算逻辑:将迭代得到的根ξ作为Xₙ,将区间端点a、b分别对应为Xₙ₋₁和Xₙ₊₁
  • 收到的反馈:“收敛参数的计算仍不正确,按该逻辑得到的结果永远为1,请严格使用任务给定的公式实现”

完整实现代码

#include<stdio.h>
#include<math.h>
#include<time.h>

double f(double x); // 目标函数
int res(int i, double a, double b, double ξ, double ε1, double ε2); // 结果打印函数
double Bisection(double a, double b, double ε1, double ε2); // 双分法实现

int main()
{
    double a=-10, b=0, ξ, h=0.5, α, x1, x2, ε1, ε2;
    int i=0;

    printf("\nf(x) = 2^x - 2 * cos(x)");
    printf("\nStart of the interval a = %.0lf", a);
    printf("\nEnd of the interval b = %.0lf", b);
    printf("\nEnter error ε1 for function = ");
    scanf("%lf", &ε1);
    printf("\nEnter error ε2 for argument = ");
    scanf("%lf", &ε2);
    printf("\n\nSOLUTION:");

    // 逐段筛查存在根的区间
    x1=a;
    x2=x1+h;
    while (x2<=b)
    {
        if ((f(x1)*f(x2))<0) 
        {
            i++;
            printf("\n\n%d) %d root of the function is in the interval [%.1f, %.1f]\n",i, i, x1, x2);
            printf("\nn\t     a\t\t   b\t\t ξ\t     f(ξ)\t     ε1\t\t    ε2\n");
            Bisection(x1,x2,ε1,ε2); // 调用双分法求解当前区间的根
        }
        x1=x2;
        x2=x1+h;
    }
    return 0;
}

// 目标函数定义
double f(double x) 
{
   double y;
   y=pow(2,x)-2*cos(x);
   return y;
}

// 打印每次迭代结果
int res(int i, double a, double b, double ξ, double ε1, double ε2) 
{
   printf("%d\t%10.7f    %10.7f    %10.7f    %10.7f    %e    %e\n", i, a, b, ξ, f(ξ), ε1, ε2);
   return 0;
}

// 双分法核心实现
double Bisection(double a, double b, double ε1, double ε2)
{
    double ξ=(a+b)/2; // 区间初始中点
    double α;
    int i=0;
    if (f(ξ)==0) 
    {
        printf("Root: %f \n\n", ξ);
    }
    else 
    {
        while ((fabs(f(ξ))>ε1) && ((fabs(b-a)/2)>ε2)) // 迭代终止条件
        {
            if ((f(a)*f(ξ))<0) 
            {
                b=ξ;
            }
            else 
            {
                a=ξ;
            }
            ξ=(a+b)/2;
            res(i+1, a, b, ξ, ε1, ε2); // 打印当前迭代结果
            i++;
        }
        α = fabs(ξ-b)/fabs(ξ-a); // 当前的收敛参数计算逻辑
        printf("\nParameter of convergence: α=%.1f\n", α);
        printf("Root ξ=%.7f found after %d iterations\n", ξ, i);
        printf("Function f(ξ)=%.10f found after %d iterations\n", f(ξ), i);
    }
    return 0;
}

运行结果截图

程序运行结果

内容的提问来源于stack exchange,提问作者Gelios

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.24 05:36:03