dat*_*ili 14 algorithm math floating-point square-root
如何创建一个返回给定nunber的sqrt的方法?
例如:sqrt(16)返回4并且sqrt(5)返回2.3 ...
我使用Java并且知道Math.sqrt()API函数但我需要方法本身.
小智 12
Java程序,无需使用任何内置函数即可找出给定数字的平方根
public class Sqrt
{
public static void main(String[] args)
{
//Number for which square root is to be found
double number = Double.parseDouble(args[0]);
//This method finds out the square root
findSquareRoot(number);
}
/*This method finds out the square root without using
any built-in functions and displays it */
public static void findSquareRoot(double number)
{
boolean isPositiveNumber = true;
double g1;
//if the number given is a 0
if(number==0)
{
System.out.println("Square root of "+number+" = "+0);
}
//If the number given is a -ve number
else if(number<0)
{
number=-number;
isPositiveNumber = false;
}
//Proceeding to find out square root of the number
double squareRoot = number/2;
do
{
g1=squareRoot;
squareRoot = (g1 + (number/g1))/2;
}
while((g1-squareRoot)!=0);
//Displays square root in the case of a positive number
if(isPositiveNumber)
{
System.out.println("Square roots of "+number+" are ");
System.out.println("+"+squareRoot);
System.out.println("-"+squareRoot);
}
//Displays square root in the case of a -ve number
else
{
System.out.println("Square roots of -"+number+" are ");
System.out.println("+"+squareRoot+" i");
System.out.println("-"+squareRoot+" i");
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个版本使用牛顿方法,这是计算sqrt的最常用方法,并且不会检查输入实际上是一个整数,但它应该可以很好地解决你的问题.
int num = Integer.parseInt(input("Please input an integer to be square rooted."));
while(0.0001 < Math.abs(guess * guess - num)){
guess = (guess + num / guess) / 2;
}
output(Integer.toString(guess));
Run Code Online (Sandbox Code Playgroud)
第二行检查当前猜测与真实结果的接近程度,如果足够接近则打破循环.第三行使用牛顿方法来更接近sqrt的真实值.我希望这有帮助.:)
这是需要考虑的事情:
要找到一个平方根,你只需要找到一个数字,它被提升到2的幂(尽管只是通过编程方式单独乘以;))返回输入.
所以,先猜一猜.如果产品太小,猜测更大.如果新产品太大,你就把它缩小了 - 猜猜介于两者之间.你看我要去哪里......
根据您对精度和/或性能的需求,当然有很多方法.在这篇文章中暗示的解决方案绝不是这两个类别中最好的解决方案,但它为您提供了一条途径的线索.
小智 5
我发明的(如果情况可能是重新发明的)是这样的:
下一个猜猜 = ((猜2)+ N)/(2×猜猜)
例:
平方根10,首先猜测是,让我们说,10:
Guess1 = (100+10)/20=5.5
Guess2 = (30.25+10)/(2*5.5)= 3.6590909090...
Guess3 = (13.3889+10)/(3.65909090*2)=3.196005082...
Run Code Online (Sandbox Code Playgroud)
等等
得到你3.16227766......或者说.
这实际上是我原始方法的简化版本
猜猜+((N +猜2)/(2×猜猜))
这看起来很像Bakhshali的方法.