繁体   English   中英

幂函数,用于找到指数为小数且小于1的幂

[英]power function to find the power where exponent is in decimal and less than 1

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

假设我们必须找到

5 0.76

我真正尝试过的是我将0.76写为76/100,它将是5 76/100 ,之后我写了 100√5^ 76

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

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 

   +
   -
   *
   /

帮我提出你的想法。

提前致谢

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_sqrt以给出newtons_nth_root ...,但随后您必须找出0.76 == 76/100(这肯定不是太难了)

您可以将数字转换为复数形式,然后使用de Moivre公式根据法律要求计算数字的第n个根。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM