algorithm - 如何在不使用内置函数的情况下计算数字的平方根?

标签 algorithm math floating-point square-root

<分区>

我如何创建一个返回给定数字的平方根的方法?

例如:sqrt(16) 返回 4 而 sqrt(5) 返回 2.3 ...
我正在使用 Java 并且知道 Math.sqrt() API 函数,但我需要方法本身。

最佳答案

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");
    }

  }
}

关于algorithm - 如何在不使用内置函数的情况下计算数字的平方根?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3051602/

相关文章:

c++ - 确定性地检查一个大数是素数还是合数?

MySQL JSON存储不同的浮点值

algorithm - 橡皮筋和钉子游戏

javascript - React中的增量 float 、字符串转换、状态表示

c++ - BST前序遍历并将树内容写入临时数组

用曲线连接图中点的算法

floating-point - FLOAT类型值存储示例问题

c++ - 将值为 0.0f 的 float 转换为 boolean 值是否安全?

algorithm - 如何绘制树结构? (二维空间分配树递归算法?)

algorithm - 将照片更改为水彩画