zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    enumerate函数和zip函数返回的对象,都需要用list()函数转换为列表
    zip函数
    列表和元组的互相转换
    元组和列表的区别
    帮小朋友写的第一个程序
    remove del pop的区别
    如何运用Linux进行查看tomcat日志
    Linux大全
    liunx中组合查询的命令
    常见的问题
  • 原文地址:https://www.cnblogs.com/ChangeG1824/p/11707905.html
Copyright © 2011-2022 走看看