溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

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

發(fā)布時(shí)間:2021-07-01 16:35:31 來(lái)源:億速云 閱讀:2088 作者:Leah 欄目:編程語(yǔ)言

Java中Math.pow()方法如何使用,相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。

使用 Java 開(kāi)發(fā)移動(dòng)設(shè)備應(yīng)用程序時(shí),可能需要用到特定 Java VM 所沒(méi)有的數(shù)學(xué)方法。本文將專(zhuān)門(mén)解決 Java ME 沒(méi)有“冪”方法 Math.pow() 的問(wèn)題。我們將演示使用三種不同的方法開(kāi)發(fā)同一個(gè) ME 應(yīng)用程序,并從中選出***的編程解決方案。

要討論此問(wèn)題,我們先考察整數(shù)和分?jǐn)?shù)冪參數(shù),將我們的分析限于正實(shí)數(shù)。我們將演示求整數(shù)問(wèn)題和小數(shù)問(wèn)題的解集相對(duì)而言比較容易(而不考慮指數(shù)的符號(hào))。在大多數(shù)情況下,我們將使用示例問(wèn)題 n = 82/3,其中我們會(huì)求出 n 的良好估計(jì)或?qū)嶋H解。如果初始指數(shù)事先不可用,則此問(wèn)題的其他解(包括牛頓法和割線法)不易編程。雖然二分法是可行的解決方案,但我們將關(guān)注傳統(tǒng)上不為人所探究的三個(gè)方法。***個(gè)是簡(jiǎn)單的(不過(guò)有時(shí)效率低下)幾何衰變算法;而第二個(gè)方法將利用 Math.sqrt() 方法并保證在不超過(guò) 11 次迭代中收斂到一個(gè)近似解。第三個(gè)方法將使用泰勒級(jí)數(shù)逼近法求對(duì)數(shù)并對(duì)泰勒級(jí)數(shù)進(jìn)行歐拉轉(zhuǎn)換。

產(chǎn)生整數(shù)解的 ME Math.pow() 方法

傳統(tǒng)上,Java Math.pow() 方法包含兩個(gè)參數(shù)。這兩個(gè)參數(shù)包括底數(shù)和指數(shù)。我們假定(最初)這兩個(gè)參數(shù)均為整數(shù),然后求出 ME 中與 Java 方法使用相同參數(shù)的 Math.pow() 方法的可編程解。此處,可編程解相當(dāng)簡(jiǎn)單,如示例 1 所示。在本例中,我們僅運(yùn)行以指數(shù)值為指標(biāo)的倍乘循環(huán)。

示例 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 }

當(dāng)然,有人可能會(huì)發(fā)現(xiàn)需要求出非整數(shù)冪的值。正實(shí)數(shù)的簡(jiǎn)單解(無(wú)需訪問(wèn) Math.pow() 方法)可能涉及使用 Math.log()。例如,請(qǐng)考慮 82/3 的情況。利用 2/3*ln(8) = 1.386294361 中自然對(duì)數(shù)的結(jié)果。要得到最終解,需要利用指數(shù) 1.386294361(特別指出 e1.386294361 = 4)。在這種情況下,可能不需要使用冪函數(shù)。遺憾的是,Java ME 也不支持 Math.log() 方法。沒(méi)有 Math.pow() 或 Math.log() 方法時(shí),我們會(huì)考慮使用樸素的“強(qiáng)力”試探性方法,應(yīng)用 Math.sqrt() 方法以及自然對(duì)數(shù)(和歐拉 e)的泰勒級(jí)數(shù)逼近來(lái)求得 Java ME 問(wèn)題的解。

使用幾何衰變算法作為強(qiáng)力解的 ME Math.pow()

Java ME 的早期實(shí)現(xiàn)包括浮點(diǎn)主數(shù)據(jù)類(lèi)型 float 和 double。最近,已添加了這些類(lèi)型。現(xiàn)在我們將 Math.pow() 聲明中的整型參數(shù)替換為 double 數(shù)據(jù)類(lèi)型。

可能需要在 Java ME Math.pow() 冪方法中使用小數(shù)指數(shù)。我們提供的生成 Math.pow() 的***種方法是使用幾何衰變算法的樸素的“強(qiáng)力”試探性方法。簡(jiǎn)單而言,衰變算法以一個(gè)大于已知解的值開(kāi)始,然后應(yīng)用某個(gè)方法來(lái)衰變?cè)撝?,直到該值非常逼近該解(有關(guān)簡(jiǎn)單線性衰變算法的演示,請(qǐng)參見(jiàn)示例 2)。在我們的例子中,將進(jìn)一步演示向上述解收斂的幾何形式。

示例 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 開(kāi)始遞減,直到找到預(yù)期的數(shù)字,假定預(yù)期數(shù)字是一個(gè)正整數(shù)。這種類(lèi)型的算法構(gòu)成了強(qiáng)力試探性方法的基礎(chǔ)。

使用類(lèi)似的方法,我們可在遇到小數(shù)時(shí)應(yīng)用此算法。假定我們需要求出 n 的值,其中 n = 82/3。要使用衰變算法,我們必須首先找到一個(gè)合適的起點(diǎn),該點(diǎn)要等于或大于解本身。這對(duì)于帶有正指數(shù)的正實(shí)數(shù)很容易做到。對(duì)于我們的示例,要對(duì)此解進(jìn)行編程,對(duì)方法兩邊求立方,得到 n3=82 。當(dāng)然,此方程與 n3=64 等效。之后,我們的起始值將變?yōu)?64,我們知道 n 必須小于 64(因?yàn)?n3 = 64)。注意,如果限于正實(shí)數(shù),則此推導(dǎo)方法同樣適用于任何正指數(shù)值。現(xiàn)在,我們可能需要設(shè)計(jì)一個(gè)循環(huán)來(lái)產(chǎn)生 n 的“充分接近”預(yù)期數(shù)字的解。我們?cè)賮?lái)看示例 3,它適合于所有正底數(shù)和正指數(shù)。

示例 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;  }

本示例演示了衰變算法的使用方法。您會(huì)注意到,n 的值(解的估計(jì)值)將按 1% 強(qiáng)制遞減。您可能需要根據(jù)編程精度要求來(lái)改變此值。也可能考慮包括編程邏輯,該邏輯用于將前一迭代解與當(dāng)前迭代進(jìn)行比較,然后,如果有改善繼續(xù)進(jìn)行迭代,但是,如果解已回歸,則返回前一個(gè)值。

這里講述的解只處理正指數(shù)。如果值為負(fù)會(huì)出現(xiàn)什么情況呢?下面我們將解決這種意外情況。

處理負(fù)指數(shù)

要再增加一層復(fù)雜度,假定正在向 Math.pow() 方法傳遞負(fù)指數(shù)。在這種情況下,指數(shù)為負(fù),一種簡(jiǎn)單的解決方案是將底數(shù)轉(zhuǎn)換為小數(shù),使指數(shù)為正。例如,8-2 可轉(zhuǎn)換為 (1/8)2。我們以可編程的方式用底數(shù) x 來(lái)除 1,用 -1 來(lái)乘 y(參見(jiàn)示例 6)。

示例 6

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

現(xiàn)在,我們已經(jīng)討論了用于在 Java ME 中估計(jì)冪函數(shù)的“強(qiáng)力”幾何衰變算法。讀者會(huì)注意到,對(duì)于較大的底數(shù)和指數(shù)分子組合,樸素的“強(qiáng)力”試探性方法有性能問(wèn)題。請(qǐng)考慮示例 85/2。使用此算法的起始值將為 85 = 32,768。如果使用 1% 的衰變,則要求全部 5196 次迭代都求該解,這樣幾乎達(dá)不到***。謹(jǐn)記此事實(shí)并且不提供改善的試探性搜索算法,我們轉(zhuǎn)到二次逼近,這會(huì)提供更多合理的迭代要求。

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

開(kāi)發(fā)我們的 Math.pow() 方法的第二種方法是通過(guò)使用 Math.sqrt() 方法(參見(jiàn)示例 7)。使用Math.sqrt() 方法要求我們對(duì)具有偶分母的冪進(jìn)行估計(jì)。例如,n = 82/3 => n3 = 82 是一個(gè)棘手問(wèn)題,因?yàn)槲覀冃枰⒎礁?,而非平方根。為了調(diào)整示例中的此問(wèn)題,我們我們就對(duì)兩端再求一次平方:n3 = 82 => n6 = 84。然后,我們就可以繼續(xù)進(jìn)行,恰好在兩次迭代之內(nèi)求出解。

當(dāng)然,我們的 ME Math.pow() 方法的指數(shù)不會(huì)以分子和分母的形式開(kāi)始,而是向我們傳遞一個(gè)實(shí)數(shù)。我們將此實(shí)數(shù)轉(zhuǎn)換為具有偶分母的小數(shù),然后利用相應(yīng)的平方根數(shù)來(lái)對(duì)
n 求解。在我們的 n = 82/3 示例中,我們進(jìn)行如下轉(zhuǎn)換:
n = 82/3 => n = 8683/1024 => n1024 = 8683
我們選擇 1024 作為分母,因?yàn)閷?duì)平方根函數(shù)迭代 10 次將得到 n 的值。特別指出,(n1024)(1/(2^10)) = n。當(dāng)然,我們可能需要根據(jù)方程右側(cè)的大小來(lái)減少迭代次數(shù)。示例 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;  }

自然對(duì)數(shù)和歐拉 e 的泰勒級(jí)數(shù)逼近

對(duì)于正實(shí)數(shù)產(chǎn)生 Math.pow() 方法最簡(jiǎn)便的方式之一是鏈接幾個(gè)方法,包括使用 泰勒級(jí)數(shù)。假定我們需要冪 y = xb。該式與 ln(y) = b*ln(x) 等價(jià)。進(jìn)而,我們可以使用泰勒級(jí)數(shù)擴(kuò)展估算 x 的自然對(duì)數(shù),如下所示。

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 的整個(gè)域?yàn)檫@些方程所覆蓋。此交錯(cuò)級(jí)數(shù)可以提供對(duì)底數(shù)對(duì)數(shù)的非常接近的逼近。用指數(shù)乘以此對(duì)數(shù)將得到 ln(y),方程的右側(cè) ln(y)=b*ln(x)?,F(xiàn)在,我們僅需求出 eln(y) 即可完成運(yùn)算。我們使用另一個(gè)泰勒級(jí)數(shù)擴(kuò)展來(lái)完成此過(guò)程:ex = 1 + x + x2 / 2! + x3 / 3! + … 使用這兩個(gè)公式,即可求得問(wèn)題的解,如示例 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  }

幾乎在所有情況下,由泰勒級(jí)數(shù)逼近返回的估計(jì)比衰變算法方法更為精確,而 Math.sqrt() 也可以產(chǎn)生更好的結(jié)果。泰勒級(jí)數(shù)方法所使用的計(jì)算周期較少, 但在值趨于 0 時(shí)會(huì)不穩(wěn)定。Math.sqrt() 結(jié)果可以提供良好的逼近,通常到第三位數(shù)字。有關(guān)使用多個(gè)任意分配的正實(shí)型變量的方法的比較,請(qǐng)參見(jiàn)表 1。我們可以看到,對(duì)于實(shí)際應(yīng)用, Math.sqrt() 或泰勒級(jí)數(shù)方法對(duì)于是大多數(shù)值都比較優(yōu)良。

表 1:衰變算法和平方根方法的比較

底數(shù),指數(shù) 實(shí)際結(jié)果 泰勒級(jí)數(shù)逼近 Math.sqrt() 估計(jì)值 衰變算法估計(jì)值

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

看完上述內(nèi)容,你們掌握J(rèn)ava中Math.pow()方法如何使用的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI