C++ 二分法程式


給定函式 f(x),以及數字 a 和 b,其中 f(a) * f(b) > 0,並且函式 f(x) 應該位於 a 和 b 之間,即 f(x) = [a, b]。任務是使用二分法找到函式 f(x) 在區間 a 和 b 之間存在的根的值。

什麼是二分法?

二分法用於在給定由 'a' 和 'b' 定義的限制範圍內找到函式 f(x) 中根的值。函式的根可以定義為使得 f(a) = 0 的值 a。

示例

Quadratic equation F(x) =  - 8
This equation is equals to 0 when the value of x will be 2 i.e.  - 8 = 0
So, root of this quadratic function F(x) will be 2.

現在,如果函式 f(x) 在給定區間 [a..b] 內連續,並且 f(a) 的符號 ≠ f(b) 的符號,那麼將存在一個屬於區間 a 和 b 的值 m,使得 f(m) = 0

值 m [a..b] 使得 f(m) = 0

即 m 是根的值,它可能是多個

下圖顯示了區間 f(a) 和 f(b)。為了找到這些區間之間的根,將限制劃分為多個部分並存儲在變數 m 中,即:

m = (a + b) / 2

在限制劃分後,將生成新的區間,如下面的圖所示

示例

Input-: x^3 - x^2 + 2 ; a =-500 and b = 100
Output-: The value of root is : -0.991821
Input-: x^3 - x^2 + 2 ; a =-200 and b = 300
Output-: The value of root is : -1.0025

我們在下面程式中使用的方案如下:

  • 輸入方程以及區間 a 和 b 的值
  • 將區間劃分為:m = (a + b) / 2
    • 列印 m 是根
  • 如果 f(m) ≠ 0
    • 檢查 f(a) * f(m) < 0
    • 則根將位於 a 和 m 之間
    • 檢查 f(b) * f(m) < 0
    • 則根將位於 b 和 m 之間

演算法

Start
Step 1-> In function double solution(double x)
   Return x*x*x - x*x + 2
Step 2-> In function bisection(double a, double b)
   If solution(a) * solution(b) >= 0 then,
      Print "You have not assumed right a and b "
      Return
   End If
   Set c = a
   Loop While (b-a) >= EP
      Set c = (a+b)/2
      If solution(c) == 0.0
         Break
      End If
      Else if solution(c)*solution(a) < 0
         Set b = c
      End Else If
      Else
         Set a = c
      End Else
   End
   Print "The value of root”
Step 3-> In function int main()
   Declare and Initialize inputs  a =-500, b = 100
   Call function bisection(a, b)
Stop

示例

線上演示

#include <iostream>
using namespace std;
#define EP 0.01
// An example function whose solution is determined using
// Bisection Method. The function is x^3 - x^2 + 2
double solution(double x) {
   return x*x*x - x*x + 2;
}
// Prints root of solution(x) with error in EPSILON
void bisection(double a, double b) {
   if (solution(a) * solution(b) >= 0) {
      cout << "You have not assumed right a and b\n";
      return;
   }
   double c = a;
   while ((b-a) >= EP) {
      // Find middle point
      c = (a+b)/2;
      // Check if middle point is root
      if (solution(c) == 0.0)
         break;
       // Decide the side to repeat the steps
      else if (solution(c)*solution(a) < 0)
         b = c;
      else
         a = c;
   }
   cout << "The value of root is : " << c;
}
 // main function
int main() {
   double a =-500, b = 100;
   bisection(a, b);
   return 0;
}

輸出

The value of root is : -0.991821

更新於: 2019-12-20

15K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.