File tree Expand file tree Collapse file tree 4 files changed +90
-0
lines changed Expand file tree Collapse file tree 4 files changed +90
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## 每日一题 - mySqrt
2
+
3
+ ### 信息卡片
4
+
5
+ - 时间:2019-06-21
6
+ - 题目链接:- (但是 leetcode 上有一个相似的题目https://leetcode.com/problems/sqrt-x/ )
7
+ - tag:` binary search ` ` math `
8
+
9
+ ### 题目描述
10
+
11
+ ```
12
+ 要求不用数学库,求 sqrt(2)精确到小数点后 10 位
13
+ ```
14
+
15
+ ### 参考答案
16
+
17
+ 1 . 二分法
18
+
19
+ 这个解法比较直接,就是普通的二分。
20
+ 通过每次取中间值进行比较,我们可以舍去一半的结果。时间复杂度logn
21
+
22
+ 参考代码:
23
+
24
+ ``` js
25
+ function sqrt (num ) {
26
+ if (num < 0 ) return num;
27
+ let start = 0 ;
28
+ let end = num;
29
+ let mid = num >> 1 ;
30
+ const DIGIT_COUNT = 10 ;
31
+ const PRECISION = Math .pow (0.1 , DIGIT_COUNT );
32
+ while (Math .abs (+ (num - mid * mid).toFixed (DIGIT_COUNT )) > PRECISION ) {
33
+ mid = start + (end - start) / 2.0 ;
34
+ if (mid * mid < num) {
35
+ start = mid;
36
+ } else {
37
+ end = mid;
38
+ }
39
+ }
40
+
41
+ return mid;
42
+ }
43
+ ```
44
+
45
+ 2 . 牛顿迭代法
46
+
47
+ 这种方法是牛顿发明的,比较巧妙。
48
+ 其实上述问题可以转化为x^2-a = 0,求x的值。其实也就是曲线和y轴交点的横坐标。
49
+ 我们可以不断用f(x)的切线来逼近方程 x^2-a = 0的根。
50
+ 根号a实际上就是x^2-a=0的一个正实根,由于这个函数的导数是2x。
51
+ 也就是说,函数上任一点(x,f(x))处的切线斜率是2x。
52
+ 那么,x-f(x)/(2x)就是一个比x更接近的近似值。代入 f(x)=x^2-a得到x-(x^2-a)/(2x),也就是(x+a/x)/2。
53
+
54
+ ![ 2019-06-27] ( ../assets/daily/2019-06-27.gif )
55
+
56
+ (图片来自Wikipedia)
57
+
58
+ 参考代码:
59
+
60
+ ``` js
61
+ function sqrtNewton (n ) {
62
+ if (n <= 0 ) return n;
63
+
64
+ let res;
65
+ let last;
66
+ const DIGIT_COUNT = 10 ;
67
+ const PRECISION = Math .pow (0.1 , DIGIT_COUNT );
68
+
69
+ res = n;
70
+
71
+ while (Math .abs (last - res) > PRECISION ) {
72
+ last = res;
73
+ res = (res + n / res) / 2 ;
74
+ }
75
+
76
+ return res;
77
+ }
78
+ ```
79
+
80
+ ### 其他优秀解答
81
+
82
+ ```
83
+ 暂无
84
+ ```
Original file line number Diff line number Diff line change @@ -77,3 +77,9 @@ tag: `sql`
77
77
78
78
时间: 2019-06-21
79
79
80
+ ### [ mySqrt] ( ./2019-06-27.md )
81
+
82
+ tag: ` inary search ` ` math `
83
+
84
+ 时间: 2019-06-27
85
+
You can’t perform that action at this time.
0 commit comments