21xrx.com
2025-04-01 04:12:01 Tuesday
文章检索 我的文章 写文章
Java中如何开根号:代码案例详解
2023-06-17 20:45:22 深夜i     56     0
Java 开根号 Math库 BigInteger类

开根号是数学中经常用到的运算,那么在Java中如何实现呢?本文将通过代码案例来详细讲解Java中开根号的实现方式。

在Java中,开根号可以通过Math库中的sqrt()方法来实现。该方法的作用是返回其参数的平方根。具体的代码实现如下:

double x = 16;
double result = Math.sqrt(x);
System.out.println(result); // 输出4.0

上述代码中,我们先定义了一个double类型的变量x,并赋值为16,然后调用Math.sqrt()方法来计算x的平方根,并将结果赋值给了result变量。最后,使用System.out.println()方法将结果输出到屏幕上。

除了Math库中的sqrt()方法外,我们还可以使用Java中的BigInteger类来实现更精确的开根号计算。具体的代码实现如下:

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
public class Sqrt {
  public static void main(String[] args) {
    BigInteger n = new BigInteger("16");
    System.out.println(sqrt(n));
  }
  public static BigDecimal sqrt(BigInteger n) {
    if (n.signum() < 0) {
      throw new IllegalArgumentException("Can't take sqrt of negative number");
    }
    if (n.equals(BigInteger.ZERO) || n.equals(BigInteger.ONE)) {
      return new BigDecimal(n);
    }
    BigInteger a = BigInteger.ONE;
    BigInteger b = n.shiftRight(5).add(BigInteger.valueOf(8));
    while (b.compareTo(a) >= 0) {
      BigInteger mid = a.add(b).shiftRight(1);
      if (mid.multiply(mid).compareTo(n) > 0) {
        b = mid.subtract(BigInteger.ONE);
      } else {
        a = mid.add(BigInteger.ONE);
      }
    }
    return new BigDecimal(a.subtract(BigInteger.ONE)).setScale(10, RoundingMode.DOWN);
  }
}

上述代码中,我们先创建了一个BigInteger类型的变量n,并赋值为16。然后调用了sqrt()方法来计算n的平方根,并使用System.out.println()方法将结果输出到屏幕上。

  
  

评论区