java math平方,使用Math.pow在Java中对数字进行平方得到精度错误

本文指导如何在Java中正确使用Math.pow()计算2的幂,并避免double到long的隐式转换误差。提出使用位移运算和整数乘法替代,同时讨论了为何避免double类型和Math.pow(),并提供了解决方案。
摘要由CSDN通过智能技术生成

I have do to a question to write a method to input an array of type LONG that stores the values of all the powers of 2 from 0 to 63 (i.e. 20 to 263)

Output the contects of the array screen.

Hint: Math.pow(x,y) is ued to put number x to exponent y

so far I have something like

I keep getting error or Math.pow(size,2); required long, found double.

I tried Math.pow(i,2); I get same error./ possible loss of precision ,, any help :) thanks

class ws3q2

{

public static void main(String[]args)

{

int ARRAY_SIZE = 5;

long size = ARRAY_SIZE;

long[] array = new long[ARRAY_SIZE];

for(int i = 0; i < ARRAY_SIZE; ++i)

{

array[i] = Math.pow(size,2);

}

}

}

解决方案

Better shift

For 2x where x ∈ ℕ, you are better off writing this as a bit shift

1L << x

instead of a floating point exponentiation

pow(2, x)

both in terms of precision and in terms of performance. In fact, 1L << x is so easy to compute that I'd prefer writing that instead of array[x], so you might perhaps avoid the array altogether.

More errors?

pow(x, 2) as you write in your code would be x2 which you could compute more easily as x*x. So which one is it to be, powers of two or squares?

Furthermore, you write pow(size,2) which uses size and does not depend on i. So all values of your array would be equal. I guess that is not what you meant.

Where your error comes from

The reason of the error message is the fact that the result of Math.pow is double, and implicit conversion from double to long is forbidden in Java. You'd have to write an explicit cast, i.e. (long)pow(2, x). But that does round towards zero, so a slight numeric error might cause a wrong result. The only exactness guarantee you have for Math.pow is this:

The computed result must be within 1 ulp of the exact result.

You could add 0.5 before doing the conversion, or use Math.round instead of the cast, but as you see, you have to know a lot about the internal workings of floating point math to get this correct. Better to stick to integer math and avoid double and Math.pow altogether.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值