02 二分法迭代求零点

感谢Python与机器学习算法频道。
接着来学二分法迭代求零点。

01

对于区间 [ a , b ] [a,b] [a,b]上单调连续函数 y = f ( x ) y=f(x) y=f(x,若 f ( a ) × f ( b ) < 0 f(a)×f(b)<0 f(a)×f(b)<0,通过不断地把函数 f ( x ) f(x) f(x)的零点所在区间一分为二,使区间的两个端点逐步逼近零点(一个解),进而得到零点近似值的方法叫二分法。

02

这种方法的局限性:如上,二分求解,给定的初始区间 [ a , b ] [a,b] [a,b],必须满足 f ( a ) × f ( b ) < 0 f(a)×f(b)<0 f(a)×f(b)<0,并且这种方法只能找到一个单根。

二分求解最重要是的找出缩小区间的条件。

二分区间 [ a , b ] [a,b] [a,b],得到区间的中间点 m i d = a + ( b − a ) / 2.0 mid = a + (b-a)/2.0 mid=a+(ba)/2.0;

  • 如果 f ( m i d ) ⋅ f ( b ) < 0 f(mid)· f(b)< 0 fmidfb<0,则可以缩小区间, a = m i d a = mid a=mid;
  • 如果 f ( a ) ⋅ f ( m i d ) < 0 f(a)· f(mid)< 0 fafmid<0,则可以缩小区间, b = m i d b = mid b=mid
  • 如果 f ( m i d ) < t h r e s h o l d f(mid) < threshold f(mid)<threshold,则认为 mid 就是方程的根;

3 Python实现

def biSection(a,b,threshold,f):
    iter=0
    while a f ( x ) = x ∗ x − 11 ∗ x + 10 , a = 5 , b = 50 , t h r e s h o l d = 1 e − 10 f(x) = x*x-11*x+10,a=5, b=50, threshold=1e-10 f(x)=xx11x+10,a=5,b=50,threshold=1e10,这个方程的解: 1,10,因此在(5,50)的解为10;
结果为:

1 a= 5, b= 27.5
2 a= 5, b= 16.25
3 a= 5, b= 10.625
4 a= 7.8125, b= 10.625
5 a= 9.21875, b= 10.625
6 a= 9.921875, b= 10.625
7 a= 9.921875, b= 10.2734375
8 a= 9.921875, b= 10.09765625
9 a= 9.921875, b= 10.009765625
10 a= 9.9658203125, b= 10.009765625
11 a= 9.98779296875, b= 10.009765625
12 a= 9.998779296875, b= 10.009765625
13 a= 9.998779296875, b= 10.0042724609375
14 a= 9.998779296875, b= 10.00152587890625
15 a= 9.998779296875, b= 10.000152587890625
16 a= 9.999465942382812, b= 10.000152587890625
17 a= 9.999809265136719, b= 10.000152587890625
18 a= 9.999980926513672, b= 10.000152587890625
19 a= 9.999980926513672, b= 10.000066757202148
20 a= 9.999980926513672, b= 10.00002384185791
21 a= 9.999980926513672, b= 10.000002384185791
22 a= 9.999991655349731, b= 10.000002384185791
23 a= 9.999997019767761, b= 10.000002384185791
24 a= 9.999999701976776, b= 10.000002384185791
25 a= 9.999999701976776, b= 10.000001043081284
26 a= 9.999999701976776, b= 10.00000037252903
27 a= 9.999999701976776, b= 10.000000037252903
28 a= 9.99999986961484, b= 10.000000037252903
29 a= 9.999999953433871, b= 10.000000037252903
30 a= 9.999999995343387, b= 10.000000037252903
31 a= 9.999999995343387, b= 10.000000016298145
32 a= 9.999999995343387, b= 10.000000005820766
33 a= 9.999999995343387, b= 10.000000000582077
34 a= 9.999999997962732, b= 10.000000000582077
35 a= 9.999999999272404, b= 10.000000000582077
36 a= 9.99999999992724, b= 10.000000000582077
37 a= 9.99999999992724, b= 10.000000000254659
38 a= 9.99999999992724, b= 10.00000000009095
solve= 10.000000000009095

你可能感兴趣的:(机器学习,Python)