【问题标题】:Java Exponential MethodJava 指数方法
【发布时间】:2013-03-01 20:42:24
【问题描述】:

我需要编写一个方法,它将取一个基数并将其提升到任何整数幂,无论是正数还是负数。可以假设基数不会为0。

在方法中我需要调用一个递归方法并使用它。

这是我之前需要用到的递归方法:

 public static double nonNegInt(double base, int pow)
{
    if (pow == 0)
    return 1;
    else
     return base * nonNegInt(base,pow-1);   
}

所以我的问题是,有人可以帮助或告诉我如何编写我需要的方法吗?

我知道当前方法很好,但我需要在另一个方法中调用它。当我这样做时,我得到一个运行时错误

【问题讨论】:

  • 那么你的问题到底是什么?
  • sniff, sniff 这闻起来像作业...
  • 我需要帮助制作方法,我是编码新手
  • 逻辑看起来不错。而且你已经有了方法。
  • 我添加了更多信息

标签: java methods recursion raise


【解决方案1】:

您的方法是一个好的开始,尽管您需要按照您的要求处理负指数。利用x^(-n) = 1.0 / x^n这一事实。

【讨论】:

    【解决方案2】:

    这也是您处理负值的方式:

    public static double nonNegInt(double base, int pow)
    {
        if (pow == 0)
            return 1;
        else if(pow < 0)
            return (1 / nonNegInt(base, -pow));
        else
            return base * nonNegInt(base,pow-1);   
    }
    

    运行它:

    public static void main(String args[])
    {
         double result = nonNegInt(4,-1);
         System.out.println(result);  //Will print 0.25
    }
    

    当然你应该给它一个有意义的名字,因为现在它确实处理负面情况。

    【讨论】:

      【解决方案3】:
      public BigDecimal exp(BigDecimal base, BigInteger pow) {
      
          if(base == null || base.intValue() == 0 ) return BigDecimal.ZERO;
      
          BigInteger absPow = pow.abs();
      
          if(absPow.intValue() == 0) return  BigDecimal.ONE;
      
          if(absPow.intValue() == 1) return  pow.intValue() > 0 ? base :
                                                  BigDecimal.ONE.divide(base, MathContext.DECIMAL128);
      
          if(absPow.intValue() == 2) return  pow.intValue() > 0 ? base.multiply(base):
                                                  BigDecimal.ONE.divide(base.multiply(base), MathContext.DECIMAL128);
      
          BigInteger i = BigInteger.ONE;
          BigDecimal result = base;
          HashMap<BigInteger, BigDecimal> history = new HashMap<>();
          history.put(i, result);
      
          while (i.compareTo(absPow) < 0) {
      
              if(i.add(i).compareTo(absPow) <= 0) {
      
                  i = i.add(i);
                  result =  result.multiply(result);
                  history.put(i, result);
      
              } else {
      
                  BigInteger diff =  absPow.subtract(i);
      
                  for (; diff.intValue() > 0 &&  !history.containsKey(diff); diff = diff.subtract(BigInteger.ONE));
      
                  i = i.add(diff);
                  result =  result.multiply(history.get(diff));
                  history.put(i, result);
              }
      
          }
      
      
          return pow.intValue() > 0 ? result : BigDecimal.ONE.divide(result, MathContext.DECIMAL128);
      }
      

      【讨论】:

      • 请通过link了解如何提供正确答案。
      猜你喜欢
      • 2019-01-08
      • 1970-01-01
      • 2015-01-26
      • 2015-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多