我需要在Java卡中用浮动指数做2的幂。您可能知道,Java规范中禁止使用float类型。我需要做这样的手术:
short n = 2 ^ (float) (31/4)预期的n是n = 215。有人知道我怎么算这个吗?
发布于 2014-07-13 14:44:32
正如Patricia所说,计算(2^a)^(1/b)是有意义的。从您的评论中,我看到b总是4,然后就变得简单多了。
因为您总是有2的幂,并且总是需要四根,所以可以将数字a向上除以4的一部分(即2^4)和rest。剩下的只能有4个值,为此,可以使用一个查找表。我会将其编码为不动点值,例如由2^16缩放。
因此,实际上,如果quotient = a // 4和remainder = a % 4计算:2^(quotient) * (2^(remainder / 4) * 65536) // 65536,其中//表示整数除法,/表示浮点除法(我知道这是无效的,但我使用不同的操作符来表示差异)。
,这应该比使用牛顿-拉夫森反复计算平方根要快得多,也容易得多,。
我对Java不太了解,所以如果语法不正确,请原谅,但它应该大致如下所示:
public class MyClass
{
public static int[] factors;
public static void initfactors()
{
factors = new int[4];
factors[0] = 65536; // 2^(0/4) * 65536
factors[1] = 77936; // 2^(1/4) * 65536
factors[2] = 92682; // 2^(2/4) * 65536
factors[3] = 110218; // 2^(3/4) * 65536
}
// Returns 2^(a/4) as integer
public static int calc(int a)
{
int quotient = a / 4;
int remainder = a % 4; // a == 4 * quotient + remainder
int factor = factors[remainder];
// calculate 2^(a/4) * (2^(remainder/4) * 65536) / 65536
return ((1 << quotient) * factor) >> 16;
}这些因素如下所示:您只需使用计算器计算2^0、2^0.25、2^0.5、2^0.75,并将结果乘以65536 (2^16),更好地将结果舍入,这样移位不会导致数值略低于所需的值。
用法示例:
public static void main(String[] args)
{
initfactors();
int result = calc(31);
System.out.println(result);
} 你的例子:
quotient: 31 / 4 --> 7
remainder: 31 % 4 --> 3
factor: factors[3] --> 110218
result: ((1 << 7) * 110218) >> 16 --> 128 * 110218 / 65536 --> 215. 发布于 2014-07-13 05:26:58
为了扩展我的评论,并给出一个部分的答案,请考虑将2^(a/b)计算为(2^a)^(1/b)。
将2提高到整数幂很容易:1 << a。根据所涉及的数字,您可能需要某种形式的扩展精度,例如手动使用两个int变量。
这就需要计算整数的bth根。如果b是2的幂,则可以通过重复平方根操作来完成,例如对每个平方根使用牛顿-拉夫森。如果b可以是任何正整数,则需要更复杂的方法。
解决这个问题的根本部分的一个可能的方法是二进制搜索。根必须介于1和2^ceil(a/2)之间。
https://stackoverflow.com/questions/24714639
复制相似问题