如何在不使用 math.pow for java 的情况下获取指数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23172704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:10:57  来源:igfitidea点击:

how to get exponents without using the math.pow for java

javamathpowexponent

提问by user3552056

This is my program

这是我的程序

// ************************************************************
    // PowersOf2.java
    //
    // Print out as many powers of 2 as the user requests
    //
    // ************************************************************

    import java.util.Scanner;

    public class PowersOf2 {

    public static void main(String[] args)

    {
        int numPowersOf2; //How many powers of 2 to compute
        int nextPowerOf2 = 1; //Current power of 2
        int exponent= 1;
        double x;

         //Exponent for current power of 2 -- this
        //also serves as a counter for the loop Scanner

        Scanner scan = new Scanner(System.in);
        System.out.println("How many powers of 2 would you like printed?");
        numPowersOf2 = scan.nextInt();
        System.out.println ("There will be " + numPowersOf2 + " powers of 2 printed");
        //initialize exponent -- the first thing printed is 2 to the what?

    while( exponent <= numPowersOf2)
        {
        double x1 = Math.pow(2, exponent);
        System.out.println("2^" + exponent + " = " + x1);
                exponent++;
        }   
//print out current power of 2
//find next power of 2 -- how do you get this from the last one?
//increment exponent

    }
}

The thing is that I am not allowed to use the math.pow method, I need to find another way to get the correct answer in the while loop.

问题是我不允许使用 math.pow 方法,我需要找到另一种方法来在 while 循环中获得正确答案。

回答by tutak

If there are no performance constraints you can do:

如果没有性能限制,您可以执行以下操作:

double x1=1;

for(int i=1;i<=numPowersOf2;i++){
   x1 =* 2
}

回答by cevaris

Here is a post that allows both negative/positive power calculations.

这是一个允许负/正功率计算的帖子。

https://stackoverflow.com/a/23003962/3538289

https://stackoverflow.com/a/23003962/3538289

Function to handle +/- exponents with O(log(n)) complexity.

处理复杂度为 O(log(n)) 的 +/- 指数的函数。

double power(double x, int n){
 if(n==0)
  return 1;

  if(n<0){
      x = 1.0/x;
      n = -n;
  }
 double ret = power(x,n/2);
 ret = ret * ret;
 if(n%2!=0)
   ret = ret * x;
 return ret;
}

回答by Marco13

Powers of 2 can simply be computed by Bit Shift Operators

2 的幂可以简单地由位移运算符计算

int exponent = ...
int powerOf2 = 1 << exponent;

Even for the more general form, you should notcompute an exponent by "multiplying ntimes". Instead, you could do Exponentiation by squaring

即使是更通用的形式,你应该通过“乘以计算的指数n时代”。相反,你可以通过平方来做

回答by wns349

You could implement your own powerfunction.

你可以实现自己的power功能。

The complexity of the powerfunction depends on your requirements and constraints. For example, you may constraint exponents to be only positive integer.

power函数的复杂性取决于您的要求和约束。例如,您可以将指数限制为仅正整数。

Here's an example of powerfunction:

下面是一个power函数示例:

public static double power(double base, int exponent) {
    double ans = 1;
    if (exponent != 0) {
        int absExponent = exponent > 0 ? exponent : (-1) * exponent;
        for (int i = 1; i <= absExponent; i++) {
            ans *= base;
        }

        if (exponent < 0) {
            // For negative exponent, must invert
            ans = 1.0 / ans;
        }
    } else {
        // exponent is 0
        ans = 1;
    }

    return ans;
}

回答by andand

It's unclear whether your comment about using a loop is a desire or a requirement. If it's just a desire there is a math identity you can use that doesn't rely on Math.Pow.

目前尚不清楚您关于使用循环的评论是愿望还是要求。如果这只是一个愿望,那么您可以使用一个不依赖于Math.Pow.

xy = ey?ln(x)

In Java this would look like

在 Java 中,这看起来像

public static double myPow(double x, double y){
  return Math.exp(y*Math.log(x));
}

If you really need a loop, you can use something like the following

如果你真的需要一个循环,你可以使用类似下面的东西

public static double myPow(double b, int e) {
  if (e < 0) {
    b = 1 / b;
    e = -e;
  }

  double pow = 1.0;
  double intermediate = b;
  boolean fin = false;

  while (e != 0) {
    if (e % 2 == 0) {
      intermediate *= intermediate;
      fin = true;
    } else {
      pow *= intermediate;
      intermediate = b;
      fin = false;
    }
    e >>= 1;
  }

  return pow * (fin ? intermediate : 1.0);
}

回答by noob.coder

// Set the variables

int numPowersOf2;        //How many powers of 2 to compute
int nextPowerOf2 = 1;    //Current power of  2
int exponent = 0;  


/* User input here */

// Loop and print results

do
   {

    System.out.println ("2^" + exponent + " = " + nextPowerOf2);

    nextPowerOf2 = nextPowerOf2*2;

    exponent ++;
  } 
while (exponent < numPowersOf2);

回答by AVos

here is how I managed without using "myPow(x,n)", but by making use of "while". (I've only been learning Java for 2 weeks so excuse, if the code is a bit lumpy :)

这是我不使用“myPow(x,n)”而是使用“while”进行管理的方法。(我只学习了 2 周 Java,所以请原谅,如果代码有点笨拙:)

    String base ="";
    String exp ="";
    BufferedReader value = new BufferedReader (new InputStreamReader(System.in));
    try {System.out.print("enter the base number: ");
        base = value.readLine();
        System.out.print("enter the exponent: ");
        exp = value.readLine(); }
    catch(IOException e){System.out.print("error");}

    int x = Integer.valueOf(base);
    int n = Integer.valueOf(exp);
    int y=x;
    int m=1;       
    while(m<n+1) {
        System.out.println(x+"^"+m+"= "+y);
        y=y*x;
        m++;    
    }

回答by mpatel

To implement pow function without using built-in Math.pow(), we can use the below recursive way to implement it. To optimize the runtime, we can store the result of power(a, b/2) and reuse it depending on the number of times is even or odd.

要在不使用内置 Math.pow() 的情况下实现 pow 函数,我们可以使用下面的递归方式来实现它。为了优化运行时间,我们可以存储 power(a, b/2) 的结果,并根据偶数或奇数的次数重复使用它。

static float power(float a, int b)
{
    float temp;
    if( b == 0)
        return 1;
    temp = power(a, b/2); 

    // if even times
    if (b%2 == 0)
        return temp*temp;
    else  // if odd times
    {
        if(b > 0)
            return a * temp * temp;
        else  // if negetive i.e. 3 ^ (-2)
            return (temp * temp) / a;
    }
} 

回答by Artemis Hunter

I know this answer is very late, but there's a very simple solution you can use if you are allowed to have variables that store the base and the exponent.

我知道这个答案很晚了,但是如果允许您拥有存储基数和指数的变量,则可以使用一个非常简单的解决方案。

public class trythis {
    public static void main(String[] args) {
        int b = 2;
        int p = 5;
        int r = 1;
        for (int i = 1; i <= p; i++) {
            r *= b;
        }
        System.out.println(r);
    }
}

This will work with positive and negative bases, but not with negative powers.

这将适用于正面和负面的基础,但不适用于负面权力。

回答by Pritam Banerjee

You can try to do this based on this explanation:

您可以尝试根据此解释执行此操作:

 public double myPow(double x, int n) {

    if(n < 0) {
        if(n == Integer.MIN_VALUE) {
            n = (n+1)*(-1);
            return 1.0/(myPow(x*x, n));
        }
        n = n*(-1);
        return (double)1.0/myPow(x, n);
    }
    double y = 1;
    while(n > 0) {
        if(n%2 == 0) {
           x = x*x; 
        }
        else {
            y = y*x;
            x = x*x;
        }
         n = n/2;
    }
    return y;   
}