温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java中Math.pow()方法如何使用

发布时间:2021-07-01 16:35:31 来源:亿速云 阅读:2033 作者:Leah 栏目:编程语言

Java中Math.pow()方法如何使用,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

使用 Java 开发移动设备应用程序时,可能需要用到特定 Java VM 所没有的数学方法。本文将专门解决 Java ME 没有“幂”方法 Math.pow() 的问题。我们将演示使用三种不同的方法开发同一个 ME 应用程序,并从中选出***的编程解决方案。

要讨论此问题,我们先考察整数和分数幂参数,将我们的分析限于正实数。我们将演示求整数问题和小数问题的解集相对而言比较容易(而不考虑指数的符号)。在大多数情况下,我们将使用示例问题 n = 82/3,其中我们会求出 n 的良好估计或实际解。如果初始指数事先不可用,则此问题的其他解(包括牛顿法和割线法)不易编程。虽然二分法是可行的解决方案,但我们将关注传统上不为人所探究的三个方法。***个是简单的(不过有时效率低下)几何衰变算法;而第二个方法将利用 Math.sqrt() 方法并保证在不超过 11 次迭代中收敛到一个近似解。第三个方法将使用泰勒级数逼近法求对数并对泰勒级数进行欧拉转换。

产生整数解的 ME Math.pow() 方法

传统上,Java Math.pow() 方法包含两个参数。这两个参数包括底数和指数。我们假定(最初)这两个参数均为整数,然后求出 ME 中与 Java 方法使用相同参数的 Math.pow() 方法的可编程解。此处,可编程解相当简单,如示例 1 所示。在本例中,我们仅运行以指数值为指标的倍乘循环。

示例 1

int pow( int x, int y) /*we define the power method with  base x and power y (i.e., x^y)*/ {  int z = x;  for( int i = 1; i < y; i++ )z *= x;  return }

当然,有人可能会发现需要求出非整数幂的值。正实数的简单解(无需访问 Math.pow() 方法)可能涉及使用 Math.log()。例如,请考虑 82/3 的情况。利用 2/3*ln(8) = 1.386294361 中自然对数的结果。要得到最终解,需要利用指数 1.386294361(特别指出 e1.386294361 = 4)。在这种情况下,可能不需要使用幂函数。遗憾的是,Java ME 也不支持 Math.log() 方法。没有 Math.pow() 或 Math.log() 方法时,我们会考虑使用朴素的“强力”试探性方法,应用 Math.sqrt() 方法以及自然对数(和欧拉 e)的泰勒级数逼近来求得 Java ME 问题的解。

使用几何衰变算法作为强力解的 ME Math.pow()

Java ME 的早期实现包括浮点主数据类型 float 和 double。最近,已添加了这些类型。现在我们将 Math.pow() 声明中的整型参数替换为 double 数据类型。

可能需要在 Java ME Math.pow() 幂方法中使用小数指数。我们提供的生成 Math.pow() 的***种方法是使用几何衰变算法的朴素的“强力”试探性方法。简单而言,衰变算法以一个大于已知解的值开始,然后应用某个方法来衰变该值,直到该值非常逼近该解(有关简单线性衰变算法的演示,请参见示例 2)。在我们的例子中,将进一步演示向上述解收敛的几何形式。

示例 2

/* This example illustrates a simplistic decay algorithm that we will assume  converges to our desired solution (a positive integer) */ int n; // assume that n is the solution to the number we are trying to find  int varX = 1000; //assume that we know the solution is less than or equal to 1000  while( varX > 0 )  {  varX -= 1; // decrement by 1  if( varX == n)return varX;  }

在示例 2 中,我们从 1000 开始递减,直到找到预期的数字,假定预期数字是一个正整数。这种类型的算法构成了强力试探性方法的基础。

使用类似的方法,我们可在遇到小数时应用此算法。假定我们需要求出 n 的值,其中 n = 82/3。要使用衰变算法,我们必须首先找到一个合适的起点,该点要等于或大于解本身。这对于带有正指数的正实数很容易做到。对于我们的示例,要对此解进行编程,对方法两边求立方,得到 n3=82 。当然,此方程与 n3=64 等效。之后,我们的起始值将变为 64,我们知道 n 必须小于 64(因为 n3 = 64)。注意,如果限于正实数,则此推导方法同样适用于任何正指数值。现在,我们可能需要设计一个循环来产生 n 的“充分接近”预期数字的解。我们再来看示例 3,它适合于所有正底数和正指数。

示例 3

double pow( double x, double y ) //we define our new power method for fractions  {  int den = 1000; // specify arbitrary denominator  int num = (int)(y*den); // find numerator  int s = (num/den)+1;  /***********************************************************************  ** Variable 's' provides the power for which we multiply the base to find  ** our starting search value. For example, if we seek a solution for  ** n = 8^(2/3), then we will use 8^2 or 64 as our starting value (which is  ** generated in our next section of code.) Why? The solution for our  ** problem (given that the base is positive) will always be less than or  ** equal to the base times the numerator power.  ************************************************************************/ /***********************************************************************  ** Because we set the denominator to an arbitrary high value,  ** we must attempt to reduce the fraction. In the example below,  ** we find the highest allowable fraction that we can use without  ** exceeding the limitation of our primitive data types.  ************************************************************************/ double z = Double.MAX_VALUE;  while( z >= Double.MAX_VALUE )  {  den -=1; // decrement denominator  num = (int)(y*den); // find numerator  s = (num/den)+1; // adjust starting value  // find value of our base number to the power of numerator  z = x;  for( int i = 1; i < num; i++ )z *= x;  }  /***********************************************************************  ** Now we are going to implement the decay algorithm to find  ** the value of 'n'.  ************************************************************************/ /***********************************************************************  ** We now find 'n' to the power of 's'. We will then decrement 'n',  ** finding the value of 'n' to the power of the denominator. This  ** value, variable 'a', will be compared to 'z'. If the 'a' is nearly  ** equal to 'z', then we will return 'n', our desired result.  ************************************************************************/ double n = x; // We define 'n' as our return value (estimate) for 'x'.  // find 'n' to the power of 's'.  for( int i = 1; i < s; i++)n *= x;  // Begin decay loop  while( n > 0 )  {  double a = n; //proxy for n  // find 'a', the value of 'n' to the power of denominator  for( int i = 1; i < den; i++ )a *= n;  // compare 'a' to 'z'. Is the value within the hundred-thousandth?  // if so, return 'n'.  double check1 = a-z;  double check2 = z-a;  if( check1 < .00001|| check2 > .00001 ) return n;  n *= .999;// We arbitrarily use a decay of .1% per iteration  }  // value could not be found, return -1.  return -1.0;  }

本示例演示了衰变算法的使用方法。您会注意到,n 的值(解的估计值)将按 1% 强制递减。您可能需要根据编程精度要求来改变此值。也可能考虑包括编程逻辑,该逻辑用于将前一迭代解与当前迭代进行比较,然后,如果有改善继续进行迭代,但是,如果解已回归,则返回前一个值。

这里讲述的解只处理正指数。如果值为负会出现什么情况呢?下面我们将解决这种意外情况。

处理负指数

要再增加一层复杂度,假定正在向 Math.pow() 方法传递负指数。在这种情况下,指数为负,一种简单的解决方案是将底数转换为小数,使指数为正。例如,8-2 可转换为 (1/8)2。我们以可编程的方式用底数 x 来除 1,用 -1 来乘 y(参见示例 6)。

示例 6

if( y < 0 )  {  x = (1/x); // convert base number to fraction  y *= -1; // make exponent positive  }

现在,我们已经讨论了用于在 Java ME 中估计幂函数的“强力”几何衰变算法。读者会注意到,对于较大的底数和指数分子组合,朴素的“强力”试探性方法有性能问题。请考虑示例 85/2。使用此算法的起始值将为 85 = 32,768。如果使用 1% 的衰变,则要求全部 5196 次迭代都求该解,这样几乎达不到***。谨记此事实并且不提供改善的试探性搜索算法,我们转到二次逼近,这会提供更多合理的迭代要求。

使用 Math.sqrt() 方法的 ME Math.pow()

开发我们的 Math.pow() 方法的第二种方法是通过使用 Math.sqrt() 方法(参见示例 7)。使用Math.sqrt() 方法要求我们对具有偶分母的幂进行估计。例如,n = 82/3 => n3 = 82 是一个棘手问题,因为我们需要立方根,而非平方根。为了调整示例中的此问题,我们我们就对两端再求一次平方:n3 = 82 => n6 = 84。然后,我们就可以继续进行,恰好在两次迭代之内求出解。

当然,我们的 ME Math.pow() 方法的指数不会以分子和分母的形式开始,而是向我们传递一个实数。我们将此实数转换为具有偶分母的小数,然后利用相应的平方根数来对
n 求解。在我们的 n = 82/3 示例中,我们进行如下转换:
n = 82/3 => n = 8683/1024 => n1024 = 8683
我们选择 1024 作为分母,因为对平方根函数迭代 10 次将得到 n 的值。特别指出,(n1024)(1/(2^10)) = n。当然,我们可能需要根据方程右侧的大小来减少迭代次数。示例 7 演示了这种方法。

示例 7

ouble pow(double x, double y)  {   //Convert the real power to a fractional form  int den = 1024; //declare the denominator to be 1024  /*Conveniently 2^10=1024, so taking the square root 10  times will yield our estimate for n. In our example  n^3=8^2n^1024 = 8^683.*/ int num = (int)(y*den); // declare numerator  int iterations = 10; /*declare the number of square root  iterations associated with our denominator, 1024.*/ double n = Double.MAX_VALUE; /* we initialize our  estimate, setting it to max*/ while( n >= Double.MAX_VALUE && iterations > 1)  {  /* We try to set our estimate equal to the right  hand side of the equation (e.g., 8^2048). If this  number is too large, we will have to rescale. */ n = x;  for( int i=1; i < num; i++ )n*=x;  /*here, we handle the condition where our starting  point is too large*/ if( n >= Double.MAX_VALUE )  {  iterations--; /*reduce the iterations by one*/ den = (int)(den / 2); /*redefine the denominator*/ num = (int)(y*den); //redefine the numerator  }  }  /*************************************************  ** We now have an appropriately sized right-hand-side.  ** Starting with this estimate for n, we proceed.  **************************************************/ for( int i = 0; i < iterations; i++ )  {  n = Math.sqrt(n);  }  // Return our estimate  return n;  }

自然对数和欧拉 e 的泰勒级数逼近

对于正实数产生 Math.pow() 方法最简便的方式之一是链接几个方法,包括使用 泰勒级数。假定我们需要幂 y = xb。该式与 ln(y) = b*ln(x) 等价。进而,我们可以使用泰勒级数扩展估算 x 的自然对数,如下所示。

ln(x) = (x-1) –(x-1)2/2 + (x-1)3/3 - (x-1)4/4….if |x-1|<=1 OR  ln(x) = 1/(x/(x-1)) + 1/(x/(x-1))2 + 1/(x/(x-1))3… if |x|>1

由于 x 为正,因而 x 的整个域为这些方程所覆盖。此交错级数可以提供对底数对数的非常接近的逼近。用指数乘以此对数将得到 ln(y),方程的右侧 ln(y)=b*ln(x)。现在,我们仅需求出 eln(y) 即可完成运算。我们使用另一个泰勒级数扩展来完成此过程:ex = 1 + x + x2 / 2! + x3 / 3! + … 使用这两个公式,即可求得问题的解,如示例 8 所示。

示例 8

double pow(double a, double b)  {  // true if base is greater than 1  boolean gt1 = (Math.sqrt((a-1)*(a-1)) <= 1)? false:true;  int oc = -1; // used to alternate math symbol (+,-)  int iter = 20; // number of iterations  double p, x, x2, sumX, sumY;  // is exponent a whole number?  if( (b-Math.floor(b)) == 0 )  {  // return base^exponent  p = a;  for( int i = 1; i < b; i++ )p *= a;  return p;  }  x = (gt1)?  (a /(a-1)): // base is greater than 1  (a-1); // base is 1 or less  sumX = (gt1)?  (1/x): // base is greater than 1  x; // base is 1 or less  for( int i = 2; i < iter; i++ )  {  // find x^iteration  p = x;  for( int j = 1; j < i; j++)p *= x;  double xTemp = (gt1)?  (1/(i*p)): // base is greater than 1  (p/i); // base is 1 or less  sumX = (gt1)?  (sumX+xTemp): // base is greater than 1  (sumX+(xTemp*oc)); // base is 1 or less  oc *= -1; // change math symbol (+,-)  }  x2 = b * sumX;  sumY = 1+x2; // our estimate  for( int i = 2; i <= iter; i++ )  {  // find x2^iteration  p = x2;  for( int j = 1; j < i; j++)p *= x2;  // multiply iterations (ex: 3 iterations = 3*2*1)  int yTemp = 2;  for( int j = i; j > 2; j-- )yTemp *= j;  // add to estimate (ex: 3rd iteration => (x2^3)/(3*2*1) )  sumY += p/yTemp;  }  return sumY; // return our estimate  }

几乎在所有情况下,由泰勒级数逼近返回的估计比衰变算法方法更为精确,而 Math.sqrt() 也可以产生更好的结果。泰勒级数方法所使用的计算周期较少, 但在值趋于 0 时会不稳定。Math.sqrt() 结果可以提供良好的逼近,通常到第三位数字。有关使用多个任意分配的正实型变量的方法的比较,请参见表 1。我们可以看到,对于实际应用, Math.sqrt() 或泰勒级数方法对于是大多数值都比较优良。

表 1:衰变算法和平方根方法的比较

底数,指数 实际结果 泰勒级数逼近 Math.sqrt() 估计值 衰变算法估计值

8.0, 0.75 4.75682846 4.7423353221144557 4.75682846 4.751286816
8.0, 0.667 4.002774 3.9919355054959973 3.994588452 3.994453662
16.0, 8.0 4294967296 4294967296 4294967296 4294752931
32.0, 5.0 33554432 33554432 33554432 33553177.47
11.0, 3.0 1331 1331 1331 1330.967224
10.0, 10.0 10000000000 10000000000 10000000000 9999699608
77.0, 3.0 456533 456533 456533 456527.6254
5.0, 15.0 30517578125 30517578125 30517578125 30516279235
15.0, 9.0 38443359375 38443359375 38443359375 38440083836
3.0, 21.0 10460353203 10460353203 10460353203 10459907131
5.0, 0.05 1.083798387 1.0837883791740017 1.083457755 1.08205432
7.0, 0.37 2.054406 2.0529191207908064 2.050973357 2.051043668
1.5, 0.789 1.377006542 1.377006541546755 1.376496289 1.376798426
1.5, 3.789 4.647397078 4.647381683179335 4.64015972 4.644836289
0.06282, 0.325784 0.405919146 0.41327102396968585 0 0.06282
0.7261, 0.20574 0.936270645 0.9362706445348806 0.93646901 0.7261
0.903272, 0.48593 0.951767579 0.951767579257642 0.951823588 0.903272
0.821111, 0.767392 0.85963221 0.8596322100794738 0.859766145 0.821111
0.24352, .004322 0.99391353 0.9939136545397182 0.994497397 0.24352
0.000125, .99556 0.000130089 627097113.1963351 0 0.000125

看完上述内容,你们掌握Java中Math.pow()方法如何使用的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI