假定我们需要求出 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 lo
|