T.J*_*.J. 9 java precision performance bigdecimal
我正在做一个问题,我必须在数字
[4 + sqrt(11)] n的小数点前找到最后两位数.
例如,当 n = 4时,[4 + sqrt(11)] 4 = 2865.78190 ......答案是65.其中n可以从2 <= n <= 10 9变化.
我的解决方案 - 我试图构建一个平方根函数,它计算11的sqrt,其精度等于用户输入的n的值.
我BigDecimal在Java中使用过以避免溢出问题.
public class MathGenius {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        long a = 0;
        try {
            a = reader.nextInt();
        } catch (Exception e) {
            System.out.println("Please enter a integer value");
            System.exit(0);
        }
        // Setting precision for square root 0f 11. str contain string like 0.00001
        StringBuffer str = new StringBuffer("0.");
        for (long i = 1; i <= a; i++)
            str.append('0');
        str.append('1');
        // Calculating square root of 11 having precision equal to number enter
        // by the user.
        BigDecimal num = new BigDecimal("11"), precision = new BigDecimal(
                str.toString()), guess = num.divide(new BigDecimal("2")), change = num
                .divide(new BigDecimal("4"));
        BigDecimal TWO = new BigDecimal("2.0");
        BigDecimal MinusOne = new BigDecimal("-1"), temp = guess
                .multiply(guess);
        while ((((temp).subtract(num)).compareTo(precision) > 0)
                || num.subtract(temp).compareTo(precision) > 0) {
            guess = guess.add(((temp).compareTo(num) > 0) ? change
                    .multiply(MinusOne) : change);
            change = change.divide(TWO);
            temp = guess.multiply(guess);
        }
        // Calculating the (4+sqrt(11))^n
        BigDecimal deci = BigDecimal.ONE;
        BigDecimal num1 = guess.add(new BigDecimal("4.0"));
        for (int i = 1; i <= a; i++)
             deci = deci.multiply(num1);
        // Calculating two digits before the decimal point
        StringBuffer str1 = new StringBuffer(deci.toPlainString());
        int index = 0;
        while (str1.charAt(index) != '.')
            index++;
        // Printing output
        System.out.print(str1.charAt(index - 2));
        System.out.println(str1.charAt(index - 1));
    }
}
此解决方案可以达到n = 200,但随后开始减速.它停止工作n = 1000.
处理问题的好方法是什么?
2 -- 53
3 -- 91
4    65
5    67
6    13
7    71
8    05
9    87
10   73
11   51
12   45
13   07
14   33
15   31
16   85
17   27
18   93
19   11
20   25
21   47
22   53
23   91
24   65
25   67
当 n=22 时,结果似乎从 n=2 的位置重复。因此,请按照与列表中相同的顺序将这 20 个值保留在数组中,例如nums[20]。
然后当用户提供 n 时:
return nums[(n-2)%20]
现在有证据证明这种模式在这里重复。
或者,如果您坚持进行详细计算;由于您通过循环乘法(而不是 BigDecimal pow(n))来计算幂,因此您可以将前面使用的数字修剪到最后 2 位数字和小数部分。
| 归档时间: | 
 | 
| 查看次数: | 1006 次 | 
| 最近记录: |