Algorithm 在不使用内置函数的情况下,如何计算数字的平方根?
如何创建一个返回给定数值的sqrt的方法 例如:sqrt(16)返回4,sqrt(5)返回2.3…Algorithm 在不使用内置函数的情况下,如何计算数字的平方根?,algorithm,math,floating-point,square-root,Algorithm,Math,Floating Point,Square Root,如何创建一个返回给定数值的sqrt的方法 例如:sqrt(16)返回4,sqrt(5)返回2.3… 我正在使用Java,并且知道Math.sqrt()API函数,但我需要该方法本身。您可能需要使用某种近似方法 看看 以下是一些需要思考的问题: 要找到一个平方根,您只需要找到一个数字,将其提升到2的幂(尽管从编程角度来说,仅仅乘以它本身要容易得多;))即可返回输入 所以,从猜测开始。如果产品太小,猜大一点。如果新产品太大,你已经缩小了范围——猜猜中间的某个地方。你知道我要去哪里 根据您对精度和/或
我正在使用Java,并且知道
Math.sqrt()
API函数,但我需要该方法本身。您可能需要使用某种近似方法
看看
以下是一些需要思考的问题: 要找到一个平方根,您只需要找到一个数字,将其提升到2的幂(尽管从编程角度来说,仅仅乘以它本身要容易得多;))即可返回输入 所以,从猜测开始。如果产品太小,猜大一点。如果新产品太大,你已经缩小了范围——猜猜中间的某个地方。你知道我要去哪里 根据您对精度和/或性能的需求,当然有很多方法。这篇文章中暗示的解决方案在这两个类别中都不是最好的,但它为您提供了一个前进方向的线索 我发明的(或者如果情况可能的话,再发明)是: 下一次猜测=((猜测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...
等等
获取您的3.16227766
。。。或者在附近
这实际上是我原来方法的简化版本
猜测+((N+猜测2)/(2×猜测))
这看起来非常像。这个版本使用牛顿法,这是计算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));
intnum=Integer.parseInt(输入(“请输入一个平方根的整数”);
而(0.0001
第二行检查当前猜测与真实结果的接近程度,如果足够接近,则中断循环。第三条线使用牛顿的方法来更接近sqrt的真实值。我希望这有帮助。:) 求给定数字的平方根的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");
}
}
}
公共类Sqrt
{
公共静态void main(字符串[]args)
{
//要找到其平方根的数字
double number=double.parseDouble(args[0]);
//这种方法求出平方根
findSquareRoot(编号);
}
/*此方法不使用
任何内置函数并显示它*/
公共静态无效findSquareRoot(双倍数字)
{
布尔值isPositiveNumber=true;
双g1;
//如果给定的数字是0
如果(数字==0)
{
System.out.println(““+number+”=“+0”的平方根);
}
//如果给定的数字是-ve数字
我能想到的唯一原因是家庭作业,所以我在标签中建议了这个。阅读“C中的数字食谱”不过,这将需要大量的处理!@ivorykoder:当然会。但是有很多方法可以智能地选择下一个猜测,以快速缩小间隔大小——大多数情况下,它归结为能够尽可能排除剩余的间隔,而不管答案在猜测的哪一边。