Weaving Wong

总觉得该写点啥...

嗨,我是Weaving,一名机器学习爱好者.


分享读书、学习、生活感悟

牛顿法与二分法求平方根

牛顿法求平方根

# __*__ coding:utf8 __*__
import math
from math import sqrt
# 利用牛顿法求平方根
def sqrt_newton(a):
    if a < 1e-6:
        return 0
    x , y = (a,0)
    count = 0
    while abs(y-x) > 0.00000001:
        count += 1
        y = x
        print(count,'\t',y)
        x = 0.5*(x + a / x)
    return x
sqrt_newton(5)
1 	 5
2 	 3.0
3 	 2.3333333333333335
4 	 2.238095238095238
5 	 2.2360688956433634
6 	 2.236067977499978





2.23606797749979

二分法求平方根

import math
def sqrt_by_dichotomy(n):
    if n < 0:
        return -1.0
    else:
        low = 0
        up = (n if n>=1 else 1) # 为防止初值n为小于1的数
        mid = (low + up) / 2;
        count=0
        while True:
            if mid**2>n:
                up = mid
            else:
                low = mid
            mid = (up+low)/2
            count +=1
            print(count,'\t',mid**2,'\t',mid)
            if (abs(mid**2 - n) < 0.0000001):
                break
        return mid
sqrt_by_dichotomy(5)
1 	 1.5625 	 1.25
2 	 3.515625 	 1.875
3 	 4.78515625 	 2.1875
4 	 5.4931640625 	 2.34375
5 	 5.133056640625 	 2.265625
6 	 4.95758056640625 	 2.2265625
7 	 5.0449371337890625 	 2.24609375
8 	 5.001163482666016 	 2.236328125
9 	 4.979348182678223 	 2.2314453125
10 	 4.990249872207642 	 2.23388671875
11 	 4.995705187320709 	 2.235107421875
12 	 4.998433962464333 	 2.2357177734375
13 	 4.999798629432917 	 2.23602294921875
14 	 5.000481032766402 	 2.236175537109375
15 	 5.000139825278893 	 2.2360992431640625
16 	 4.999969225900713 	 2.2360610961914062
17 	 5.000054525226005 	 2.2360801696777344
18 	 5.00001187547241 	 2.2360706329345703
19 	 4.999990550663824 	 2.2360658645629883
20 	 5.000001213062433 	 2.2360682487487793
21 	 4.999995881861707 	 2.236067056655884
22 	 4.999998547461715 	 2.2360676527023315
23 	 4.999999880261985 	 2.2360679507255554
24 	 5.000000546662187 	 2.2360680997371674
25 	 5.00000021346208 	 2.2360680252313614
26 	 5.000000046862032 	 2.2360679879784584





2.2360679879784584
更早的文章

七种排序方法

冒泡排序(稳定)—O(n²) 基本思想:两两比较相邻记录的关键字,如果反序则交换,直到没有反序的记录为止。def bubble_sort(alist): n = len(alist) for j in range(n - 1): count = 0 for i in range(0, n - 1 - j): if alist[i] > alist[i + 1]: alist[i], alis...…

继续阅读