java求平方根(sqrt)的代码演示
生活随笔
收集整理的這篇文章主要介紹了
java求平方根(sqrt)的代码演示
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
java 中平方根(sqrt)算法
平方根(sqrt, square root)是數(shù)學(xué)中常見的數(shù)學(xué)的公式;
使用程序進行求平方根主要分為兩步:
第一步: while()循環(huán), 控制循環(huán)次數(shù)及小數(shù)的位數(shù), 防止無限循環(huán)和出現(xiàn)多位小數(shù);
第二步: 通過分解平方根, 使用循環(huán), 逐漸減小,接近平方根;
同理, 其他方根也可以類似擴展, 不過需要注意的是,
偶數(shù)次方根需要確保輸入正數(shù);
奇數(shù)次方根需要轉(zhuǎn)換為正數(shù), 確保循環(huán)收斂, 再進行結(jié)果正負判斷;
代碼如下:
/*
* 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, 防止小數(shù)
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);
}
}
登錄后復(fù)制
輸出:
sqrt(4.0) = 2.0 cbrt(9.0) = -3.0
登錄后復(fù)制
以上就是java求平方根(sqrt)的代碼演示的詳細內(nèi)容,更多請關(guān)注風(fēng)君子博客其它相關(guān)文章!
總結(jié)
以上是生活随笔為你收集整理的java求平方根(sqrt)的代码演示的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Gateway internal_len
- 下一篇: encountered unknown