【问题标题】:power function to find the power where exponent is in decimal and less than 1幂函数查找指数为十进制且小于 1 的幂
【发布时间】:2016-08-24 04:14:42
【问题描述】:

我试图创建一个找到实数幂的程序。问题是指数是十进制的,小于1但不是负数。

假设我们必须找到的力量

50.76

我真正尝试的是我将 0.76 写为 76/100,它会是 576/100 然后我写了

如果你想看看我做了什么,这里是代码

public class Struct23 {


public static void main(String[] args) {
    double x = 45;
    int c=0;
    StringBuffer y =new StringBuffer("0.23");

    //checking whether the number is valid or not
    for(int i =0;i<y.length();i++){
        String subs = y.substring(i,i+1);


        if(subs.equals(".")){
            c=c+1;
        }     
    }
     if(c>1){ 
         System.out.println("the input is wrong");
             }
     else{
       String nep= y.delete(0, 2).toString();
        double store = Double.parseDouble(nep);
        int length = nep.length();
        double rootnum = Math.pow(10, length);
        double skit = power(x,store,rootnum);
        System.out.println(skit);

}

}
 static double power(double x,double store,double rootnum){
    //to find the nth root of number
    double number =  Math.pow(x, 1/rootnum);

     double power = Math.pow(number, store);
return power;
}

}

答案会来,但主要问题是我不能使用 pow 函数来做到这一点

我也不能使用 exp()log() 函数。

 i can only use 

   +
   -
   *
   /

帮我提出你的想法。

提前致谢

【问题讨论】:

  • 请将您的代码添加到问题中(最小示例)而不是链接
  • 你能用exp(0.76*log(5))吗?
  • 不,我不能使用 exp() 或 log()
  • 如果指数部分是整数,编写自己的幂函数非常容易。网上有很多例子。
  • @NavedAlam 我很确定他明确表示它们不是整数......但你肯定是正确的它变得非常微不足道

标签: java logic operators


【解决方案1】:
def newtons_sqrt(initial_guess, x, threshold=0.0001):
    guess = initial_guess
    new_guess = (guess+float(x)/guess)/2
    while abs(guess-new_guess) > threshold :
        guess=new_guess
        new_guess = (guess+float(x)/guess)/2
    return new_guess




def power(base, exp,threshold=0.00001):
    if(exp >= 1): # first go fast!
        temp = power(base, exp / 2);
        return temp * temp
    else: # now deal with the fractional part
        low = 0
        high = 1.0
        sqr = newtons_sqrt(base/2,base)
        acc = sqr
        mid = high / 2

        while(abs(mid - exp) > threshold):
            sqr = newtons_sqrt(sqr/2.0,sqr)

            if (mid <= exp):
                low = mid
                acc *= sqr
            else:
                high = mid
                acc *= (1/sqr)
            mid = (low + high) / 2;
        return acc

print newtons_sqrt(1,8)
print 8**0.5

print power(5,0.76)
print 5**0.76

我从https://stackoverflow.com/a/7710097/541038 挪用了大部分答案

你也可以在newtons_sqrt 上解释给newtons_nth_root ...但是你必须弄清楚 0.76 == 76/100(我确定这真的不太难)

【讨论】:

    【解决方案2】:

    您可以将您的号码转换为复杂的形式,然后使用de Moivre' formula 使用您的合法操作计算您的号码的第 n 次根。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2021-05-26
      相关资源
      最近更新 更多