以下程式碼運用了以下概念

若 f(x) 在 (a,b) "恰有一解"
則 f(a)*f(b) < 0

注意,在 (a,b) 中一定要是 "恰有一解"
如果有二個解以上的話, f(a)*f(b)<0 未必成立
故我若要知道 f(x) 於區間 (-5, 5) 內有幾個解
必需要先設一個 step, 這個 step 要保證夠小,
能夠滿足每次切開的區間都只有一個解.

// ==================================
// filename: SolRange.cpp
// find the range sol.
// author  : Edison.Shih.
// Date    : 2010.3.6
// ** all rights resever **
// ==================================

/*
  f(x) = 0 at [a, b],
  -> f(a) * f(b) <= 0
*/

#include <stdio.h>
#include <stdlib.h>

int func(double x){
      // f(x) = x^3 + 2x^2 -5x +1
      return (x*x*x + 2*x*x - 5*x + 1);
}

int main(int argc, char **argv)
{
      int x;
      for(x=-5; x<=5; x++)
      {
            if( func(x)*func(x+1) < 0 ) {
                  printf("there is a sol. at [%2d,%2d]\n", x, x+1);
            }
      }
      return 0;
}

// ==================================
執行結果

there is a sol. at [-4,-3]
there is a sol. at [ 0, 1]
there is a sol. at [ 1, 2]

arrow
arrow
    全站熱搜

    Edison 發表在 痞客邦 留言(0) 人氣()