C 语言二分法2025年3月17日 | 阅读 8 分钟 本节将讨论 C 语言中的二分法。二分法是一种简单且收敛的方法,用于求非线性方程的实根。二分法重复地将区间一分为二,并选择一个子区间,在该子区间中找到给定方程的根。 这意味着,如果函数 f(x) 在闭区间 [a, b] 中连续,并且 f(a) 和 f(b) 是两个符号相反的实数,则在 a 和 b 之间至少包含一个 f(x) = 0 的实根。此方法也称为 Bolzano 或半区间或二分搜索方法。 ![]() 二分法算法以下是 C 语言中二分法的算法。
如果 (f1 * f2) > 0,则显示初始猜测错误并将控制权转移到步骤 11。
示例 1:使用二分法查找给定方程的根的程序 让我们考虑一个示例,使用 C 语言中的二分法和 for 循环来获取方程的近似根。 输出 Enter the first starting point: 5 Enter the second ending point: 9 Enter the maximum iteration to be allowed: 8 Input the no. of allowed error point: 0.02 Iteration 1: 7.000000 Iteration 1: 8.000000 Iteration 2: 8.500000 Iteration 3: 8.750000 Iteration 4: 8.875000 Iteration 5: 8.937500 Iteration 6: 8.968750 Iteration 7: 8.984375 The approximation root is: 8.984375 示例 2:使用二分法查找方程 (x3 + 3x - 5 = 0) 的实根的程序 让我们考虑一个示例,使用 C 语言中的二分法打印实根。 输出 Display the real roots of the given equation using the Bisection method: X ^ 3 + 3 * x - 5 = 0 Enter the first approximation of the root: 1 Enter the second approximation of the root: 5 Input the number of iteration you want to perform: 7 The root after 1 iterations is 3.000000 The root after 2 iterations is 2.000000. The root after 3 iterations is 1.500000. The root after 4 iterations is 1.250000. The root after 5 iterations is 1.125000. The root after 6 iterations is 1.187500. The root after 7 iterations is 1.156250. The approximation root is 1.156250 示例 3:使用二分法查找非代数函数的近似根的程序 让我们创建一个简单的程序,使用 C 语言中的二分法和 do while 循环计算近似根。 输出 Input the initial approximation for x: 1 Input the initial approximation for y: 3 Define the input accuracy: .002 Input the maximum number of iteration: 10 Iteration x y z f(z) |x - y| 1 1.000000 3.000000 2.000000 -0.479759 2.000000 2 1.000000 2.000000 1.500000 1.015806 1.000000 3 1.500000 2.000000 1.750000 0.479383 0.500000 4 1.750000 2.000000 1.875000 0.058267 0.250000 5 1.875000 2.000000 1.937500 -0.195362 0.125000 6 1.875000 1.937500 1.906250 -0.064801 0.062500 7 1.875000 1.906250 1.890625 -0.002343 0.031250 8 1.875000 1.890625 1.882812 0.028192 0.015625 9 1.882812 1.890625 1.886719 0.012982 0.007812 10 1.886719 1.890625 1.888672 0.005334 0.003906 The root of the given equation is: 1.888672 二分法的优点
二分法的缺点
|
我们请求您订阅我们的新闻通讯以获取最新更新。