1

このプログラムは、二分法を使用して方程式を解くためのもので、「function show return a value」というエラーが表示されます。

このメソッドでは、関数が与えられ、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 であるため、2 番目のケースでは初期条件が満たされていません。

于 2015-08-27T05:13:09.640 に答える