1

该程序用于使用二分法求解方程给出错误“函数显示返回值”。

在这种方法中,我们给定一个函数f(x),我们近似 2 个根ab 对于函数,使得f(a).f(b)<0.

然后我们找到另一个点

c=(a+b)/2

if f(c)==0

then root=c;

else

if f(a).f(c)<0

b=c;

if f(b).f(c)<0

a=c;

我们对给定的迭代次数重复这些步骤

#include<stdio.h>
#include<math.h>
#define e 0.000001/*e is the prescribed accuracy*/
main()
{
   double g1,g2,g,v,v1,v2,prev;
   int found=0,converged=0,i=0;
   double f(double);
   printf("We apply Bisection method to find a real root of the non-linear equation f(x) = 0, where f(x) = x^(2.7182818)-3cosx+1n");
   while(found==0)/*This loop will continue until a range is found in between which a real root lies*/
  {
    printf("nEnter the first guess : ");
    scanf("%lf",&g1);
    v1=f(g1);
    printf("nEnter the second guess : ");
    scanf("%lf",&g2);
    v2=f(g2);

 if(v1*v2>0)
   {
       found=0;
       g1++;
       printf("nRoot does not lie in [%lf,%lf].n",g1-1,g2);
       printf("nn..Enter two new guesses..nn");/*Previous two guesses are inappropriate*/
    }
else
      found=1;
  }
     printf("nThere is a real root which lies in [%lf,%lf].n",g1,g2);   
   while(converged==0)/*This loop will continue until a real root is found*/
   {
      printf("nnIteration = %dnn",i); 
      printf("a[%d](-ve)tb[%d](+ve)tbbx[%d]=(a[%d]+b[%d])/2tf(x[%d])n",i,i,i+1,i,i,i+1);
      printf("%lft",g1);
      printf("%lft",g2);
      g=(g1+g2)/2;
      v=f(g);
      printf("%lft",g);
      printf("t%lf",v);
  if(v<0)
      g1=g;
  else
      g2=g;
if(fabs(prev-v)<e)
    converged=1;
else
    prev=v;
    i=i+1;
   }
   printf("nnThe approximate value of the root is : %lfn",g);
}
/*This function returns values of f(x)*/
double f(double x)
{
   return pow(2.7182818,x)-3*cos(x)+1;
}
4

1 回答 1

1

当使用初始值 1 和 2 以及迭代 20 进行测试时,结果为 1.154172。这是系统的根。

当使用初始值 1、1 和迭代 20 进行测试时,结果为 1.0000,这是错误的。

您应该检查是否满足根的初始条件,即 f(a) * f(b) < 0。

f(1) = -1, f(1)* f(1) = +1,因此在第二种情况下不满足初始条件。

于 2015-08-27T05:13:09.640 回答