3

I have written this C code to compare the root of two functions using bisection method. My first function (g(x)) executes correctly but the second one (h(x)) outputs "#1QO" on screen. I can't find what I did wrong in the code.

Can you please explain? Any kind of help would be highly appreciated. Thanks!

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

typedef double (*DFD) (double);

double g (double x) 
{
   double y;
   y = pow (x,3) - pow (x,2)-1;
   return y;
}

double h (double x)
{
  double k;
  k = 1.0 + (1.0/x) + (1.0 /pow (x,2));
  return k;
}

double bisection (DFD f, double x0, double x1,double tol)
{
   int i;
   double middle;
     for (i=1;i<=50;) {
     middle = (x0+x1)/2.0;
     if (fabs (middle - x0) <tol) return middle;
     if (f(middle)* f(x0) <0.0) x1 = middle;
     else x0 = middle;
     }
 }

 int main () {
 double root_gx, root_hx = 0.0;

 root_gx = bisection (g,0,2,0.0005);
 printf ("Root found using g(x) = %.3lf\n",root_gx);

 root_hx = bisection (h,1,2,0.0005);
 printf ("Root found using h(x) = %.3lf\n",root_hx);

 printf ("Difference between the two roots = %.3lf\n", (fabs (root_gx- root_hx)));

return 0;

} 

EDIT: Initialised i=1 in bisection and changed bisection (h,0,2,0.0005) to bisection (h,1,2,0.0005) and it works Thanks everyone!

4

2 回答 2

4

值未初始化导致未定义的行为。设置为某个值。

// int i;
int i = 0;
...
for (;i<=50;) {

i永远不会增加。
50 是任意的。

建议每次迭代使用doubleas half的二进制精度。bisection()

for (i=0; i <= DBL_MANT_DIG; i++) {
  ...
}
return middle;

还建议更改算法以允许更改|差异| 0.0 以满足 0.0 的容差。

// if (fabs (middle - x0) <tol) return middle;
if (fabs (middle - x0) <= tol) return middle;
于 2015-12-19T22:56:33.120 回答
1
double h (double x)
{
  double k;
  k = 1.0 + (1.0/x) + (1.0 /pow (x,2));
  return k;
}

如果 . 给出除以零x==0.0。当您调用 时,您会执行此操作bisection (h,0,2,0.0005);,即调用f(x0)h(0.0);在这种情况下。

如果在函数中除以输入参数,则应始终检查输入参数的实际值是否不等于0.0

double h (double x)
{
  if ( x == 0.0 ) return 1e99; // infinite
  double k;
  k = 1.0 + (1.0/x) + (1.0 /pow (x,2));
  return k;
}
于 2015-12-19T19:56:33.347 回答