平方根(sqrt, square root)是數學中常見的數學的公式;
使用程序進行求平方根主要分為兩步:
第一步: while()循環, 控制循環次數及小數的位數, 防止無限循環和出現多位小數;
第二步: 通過分解平方根, 使用循環, 逐漸減小,接近平方根;
同理, 其他方根也可以類似擴展, 不過需要注意的是,
偶數次方根需要確保輸入正數;
奇數次方根需要轉換為正數, 確保循環收斂, 再進行結果正負判斷;
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
/* * Algorithms.java * * Created on: 2013.12.03 * Author: Wendy */ /*eclipse std kepler, jdk 1.7*/ public class Algorithms { public static double sqrt( double c) { if (c< 0 ) return Double.NaN; //NaN: not a number double err = 1e- 15 ; //極小值 double t = c; while (Math.abs(t-c/t) > err*t) //t^2接近c, 防止小數 t = (c/t + t)/ 2.0 ; return t; } public static double cbrt( double c) { boolean b = (c> 0 ) ? true : false ; //保存c的符號 c = (c> 0 ) ? c : -c; double err = 1e- 15 ; double t = c; while (Math.abs(t*t-c/t) > err*t) t = (c/(t*t)+t)/ 2.0 ; t = (b) ? t : -t; return t; } public static void main(String[] args) { double r = sqrt( 4.0 ); System.out.println( "sqrt(4.0) = " + r); double rc = cbrt(- 27.0 ); System.out.println( "cbrt(9.0) = " + rc); } } |
輸出:
1
2
|
sqrt( 4.0 ) = 2.0 cbrt( 9.0 ) = - 3.0 |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/caroline_wendy/article/details/17114939