BigDecimal操作(开方+牛顿迭代法)

 1 import java.io.*;
 2 import java.util.*;
 3 import java.math.*;
 4 
 5 class Main  
 6 {
 7     public static void main (String[] args) throws java.lang.Exception
 8     {
 9         Scanner cin=new Scanner(System.in);
10         BigDecimal a,b,maxn,minn,k,res;
11         BigDecimal one=new BigDecimal("1");
12         BigDecimal five=new BigDecimal("5");
13         BigDecimal two=new BigDecimal("2");
14         while(cin.hasNext()){
15             a=cin.nextBigDecimal();
16             b=cin.nextBigDecimal();
17             maxn=a.max(b);
18             minn=a.min(b);
19             k=(one.add(sqrt(five,105))).divide(two);
20             res=(maxn.subtract(minn)).multiply(k);
21             res=res.setScale(0,BigDecimal.ROUND_DOWN);
22             if(res.compareTo(minn)==0)System.out.println(0);
23             else System.out.println(1);
24         }
25     }
26     public static BigDecimal sqrt(BigDecimal value, int scale){
27         BigDecimal num2 = BigDecimal.valueOf(2);
28         int precision = 100;
29         MathContext mc = new MathContext(precision, RoundingMode.HALF_UP);
30         BigDecimal deviation = value;
31         int cnt = 0;
32         while (cnt < precision) {
33             deviation = (deviation.add(value.divide(deviation, mc))).divide(num2, mc);
34             cnt++;
35         }
36         deviation = deviation.setScale(scale, BigDecimal.ROUND_HALF_UP);
37         return deviation;
38     }
39 }

 

posted @ 2019-10-20 16:08  Cherlie  阅读(2139)  评论(0编辑  收藏  举报