您的位置:首页 > 编程语言 > Java开发

创建 Java ME Math.pow() 方法 (转自SUN中国技术社区)

2008-01-08 11:02 811 查看
使用 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 所示。在本例中,我们仅运行以指数值为指标的倍乘循环。

示例[code] 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
}
[/code]
当然,有人可能会发现需要求出非整数幂的值。正实数的简单解(无需访问
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)。在我们的例子中,将进一步演示向上述解收敛的几何形式。

示例[code] 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;
}
[/code]
在示例 2 中,我们从 1000 开始递减,直到找到预期的数字,假定预期数字是一个正整数。这种类型的算法构成了强力试探性方法的基础。

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

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

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

处理负指数

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

示例[code] 6

if( y < 0 )
{
x = (1/x); // convert base number to fraction
y *= -1; // make exponent positive
}
[/code]
现在,我们已经讨论了用于在 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
[/code]
我们选择 1024 作为分母,因为对平方根函数迭代 10 次将得到
n
的值。特别指出,
(n1024)(1/(2^10)) =  n
。当然,我们可能需要根据方程右侧的大小来减少迭代次数。示例 7 演示了这种方法。

示例[code] 7

double 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^2    n^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;
}
[/code]

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

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

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

底数,指数实际结果泰勒级数逼近
Math.sqrt()
估计值
衰变算法估计值
8.0, 0.754.756828464.74233532211445574.756828464.751286816
8.0, 0.6674.0027743.99193550549599733.9945884523.994453662
16.0, 8.04294967296429496729642949672964294752931
32.0, 5.033554432335544323355443233553177.47
11.0, 3.01331133113311330.967224
10.0, 10.01000000000010000000000100000000009999699608
77.0, 3.0456533456533456533456527.6254
5.0, 15.030517578125305175781253051757812530516279235
15.0, 9.038443359375384433593753844335937538440083836
3.0, 21.010460353203104603532031046035320310459907131
5.0, 0.051.0837983871.08378837917400171.0834577551.08205432
7.0, 0.372.0544062.05291912079080642.0509733572.051043668
1.5, 0.7891.3770065421.3770065415467551.3764962891.376798426
1.5, 3.7894.6473970784.6473816831793354.640159724.644836289
0.06282, 0.3257840.4059191460.4132710239696858500.06282
0.7261, 0.205740.9362706450.93627064453488060.936469010.7261
0.903272, 0.485930.9517675790.9517675792576420.9518235880.903272
0.821111, 0.7673920.859632210.85963221007947380.8597661450.821111
0.24352, .0043220.993913530.99391365453971820.9944973970.24352
0.000125, .995560.000130089627097113.196335100.000125

编程注意事项和结论

本文已经解决了在 Java ME 中开发
Math.pow()
方法的三种途径。虽然朴素的“强力”几何衰变试探性方法比较不错,而且对于小问题可能很有用处,但是
Math.sqrt()
改写对于大多数范围的应用可能要好一些。最佳方法可能是泰勒级数逼近。显然,这三个示例均未包括完成该任务的特有方法(如二分法及参考资料中介绍的其他方 法),并且我们希望其他方法可以提供占用较少资源的更为高效的技巧。最后需要注意的一点是:如果要求您开发此类方法,务必考虑其应用,所需的参数以及预期 的结果和精度。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: