日期:2014-05-20  浏览次数:21096 次

急急,关于BigInteger类型数求开平方的问题
下面是我用BigInteger写实数Rational类的sqr()方法,其中想实现实数的开平方功能结果出错了。应该说实现这里有点问题,具体实现方法不怎么懂。看了,API,一开始打算用modPow()结果实现不了,不太懂这里。
Java code

/**Return the sqr**/
      public Rational sqr(){
          BigInteger temp1=new BigInteger(String.valueOf(Math.sqrt(numerator.doubleValue())));
          BigInteger temp2=new BigInteger(String.valueOf(Math.sqrt(denominator.doubleValue())));
          return new Rational(temp1,temp2);
      }


这里我是这样想的,先把BigInteger分子、分母转成double型然后调用,Math.sqrt()再转成String型再转BigInteger,问题就是这里出错了。。转换有问题了
下面是测试代码:
Java code

package test;
import java.math.BigInteger;
/*---- -----Exercise14_19测试类------------*/
public class Exercise14_19 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //Rational r1 = new Rational(new BigInteger("4"),new BigInteger("2"));
        //Rational r2 = new Rational(new BigInteger("2"),new BigInteger("3"));
        Rational r1 = new Rational(new BigInteger("-60000000000000000000"),new BigInteger("200000000000000000"));
        Rational r2 = new Rational(new BigInteger("20000000000000000000"),new BigInteger("300000000000000000"));
        System.out.println(r1 + " + " + r2 + " = " + r1.add(r2));
        System.out.println(r1 + " - " + r2 + " = "+ r1.subtract(r2));
        System.out.println(r1 + " * " + r2 + " = "+ r1.multiply(r2));
        System.out.println(r1 + " / " + r2 + " = "+ r1.divide(r2));
        System.out.println(r2 + " is "+r2.doubleValue() );    
        Rational r3 = new Rational(new BigInteger("4"),new BigInteger("2"));
        System.out.println(r3 + " sqr is "+r3.sqr().doubleValue());    
    }

}



运行结果如下:

[-300] + [200]/[3] = [-700]/[3]
[-300] - [200]/[3] = [-1100]/[3]
[-300] * [200]/[3] = [-20000]
[-300] / [200]/[3] = [-9]/[2]
Exception in thread "main" java.lang.NumberFormatException: For input string: "1.4142135"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.math.BigInteger.<init>(Unknown Source)
at java.math.BigInteger.<init>(Unknown Source)
at test.Rational.sqr(Rational.java:67)
at test.Exercise14_19.main(Exercise14_19.java:22)
[200]/[3] is 66.66666666666667




------解决方案--------------------
他的意思是
input string: "1.4142135" 不能转化为 Integer类型。
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
我理解为new BigInteger("不能是带小数点")。你可以试一下、
System.out.print(new BigInteger("123.0"));
事实证明我是对的,也就是你
 BigInteger temp1=new BigInteger(String.valueOf(Math.sqrt(numerator.doubleValue())));
 BigInteger temp2=new BigInteger(String.valueOf(Math.sqrt(denominator.doubleValue())));
这两句出问题了。转化为BigInteger时。

------解决方案--------------------
换成BigDecimal吧,注意BigDecimal 的divide方法 比如
new BigDecimal("2").divide(new BigDecimal("3")),你要是转化double计算就令当别论了。
多查查API。