平方根(sqrt, square root)是數(shù)學(xué)中常見的數(shù)學(xué)的公式;
使用程序進(jìn)行求平方根主要分為兩步:
第一步: while()循環(huán), 控制循環(huán)次數(shù)及小數(shù)的位數(shù), 防止無限循環(huán)和出現(xiàn)多位小數(shù);
第二步: 通過分解平方根, 使用循環(huán), 逐漸減小,接近平方根;
同理, 其他方根也可以類似擴(kuò)展, 不過需要注意的是,
偶數(shù)次方根需要確保輸入正數(shù);
奇數(shù)次方根需要轉(zhuǎn)換為正數(shù), 確保循環(huán)收斂, 再進(jìn)行結(jié)果正負(fù)判斷;
代碼如下:
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(diǎn), 防止小數(shù) t = (c/t + t)/ 2.0 ; return t; } public static double cbrt( double c) { boolean b = (c> 0 ) ? true : false ; //保存c的符號(hào) 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 |
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
原文鏈接:http://blog.csdn.net/caroline_wendy/article/details/17114939