简体   繁体   中英

Get nth digit of a sqrt: getting digits that exceed the double scope

I have this code that takes a digit and returns a value of the digit that is in that digit position in the sqrt(2) :

public static int sqrtTwo(int digit)
{
    //1.41421356237…
   double result = Math.sqrt(2.0);

   String resultString = String.valueOf(result);

   if (digit == 0)  {
       return Integer.parseInt(resultString.substring(0, 1));
   }

   if (digit + 1 >= resultString.length())  {
       digit = resultString.length() - 2;
   }

   return Integer.parseInt(resultString.substring(digit + 1, digit + 2));
}

But I can only get so many digits by using it. The Math class would return a double which is limited. I want to calculate a sqrt value up to a certain digit, be it a 100th or 500th digit, no matter. How should I do that?

I have found this code, but it looks limited by double as well:


    static double squareRoot(int number, int precision)
    {
        int start = 0, end = number;
        int mid;

        // variable to store the answer
        double ans = 0.0;

        // for computing integral part
        // of square root of number
        while (start <= end)
        {
            mid = (start + end) / 2;

            if (mid * mid == number)
            {
                ans = mid;
                break;
            }

            // incrementing start if integral
            // part lies on right side of the mid
            if (mid * mid < number) {
                start = mid + 1;
                ans = mid;
            }

            // decrementing end if integral part
            // lies on the left side of the mid
            else {
                end = mid - 1;
            }
        }

        // For computing the fractional part
        // of square root upto given precision
        double increment = 0.1;
        for (int i = 0; i < precision; i++) {
            while (ans * ans <= number) {
                ans += increment;
            }

            // loop terminates when ans * ans > number
            ans = ans - increment;
            increment = increment / 10;
        }
        return ans;
    }

the "2" in the big decimal constructor is the value of what operation you want to do, the 1000 in the MathContext is how many digits you want to get from it.

so like this is how I would get get sqrt(2) to 1000 decimal places

public static void main(String[] args) {
    BigDecimal digits = new BigDecimal("2");

    BigDecimal num = digits.sqrt(new MathContext(1000));
    System.out.println(num.toString());

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM