กำหนดด้วยฟังก์ชัน f(x) โดยมีตัวเลข a และ b โดยที่ f(a) * f(b)> 0 และฟังก์ชัน f(x) ควรอยู่ระหว่าง a และ b เช่น f(x) =[a, b ]. ภารกิจคือการค้นหาค่าของรูทที่อยู่ระหว่างช่วง a และ b ในฟังก์ชัน f(x) โดยใช้วิธีแยกสองส่วน
วิธีแบ่งเป็นสองส่วนคืออะไร
วิธี Bisection ใช้เพื่อค้นหาค่าของรูทในฟังก์ชัน f(x) ภายในขีดจำกัดที่กำหนดโดย 'a' และ 'b' รากของฟังก์ชันสามารถกำหนดเป็นค่า a ที่ f(a) =0 ได้
ตัวอย่าง
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) ก็จะมีค่า m ซึ่งเป็นของช่วง a และ b ทำให้ f(m) =0
ค่า m [a..b] เช่นนั้น f(m) =0
เช่น. m คือค่าของรูทซึ่งสามารถเป็นค่าได้หลายค่า
รับด้านล่างเป็นตัวเลขที่แสดงช่วงเวลา f(a) และ f(b) ในการค้นหารูทระหว่างช่วงเวลาเหล่านี้ ขีดจำกัดจะถูกแบ่งออกเป็นส่วนๆ และเก็บไว้ในตัวแปร m i.e.
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