开发者

first 64 bits of the fractional part of the square root of 2

开发者 https://www.devze.com 2023-01-28 13:07 出处:网络
double i=Math.sqrt(2); double fpart=i-(long)i; String s=String.valueOf(fpart); s=s.substring(2, s.length()-1);
 double i=Math.sqrt(2);
 double fpart=i-(long)i;

 String s=String.valueOf(fpart);
 s=s.substring(2, s.length()-1);

 Long b=Long.parseLong(s);
 System.out.println(Long.toBinaryString(b));

 System.o开发者_JS百科ut.println(Long.toBinaryString(b).substring(0, 63));

i'm getting StringIndexOutOfBoundsException as the strig is only 52 bits long. But, I want the first 64 bits of the fractional part of the square root of 2.


Unfortunately, you forgot one important thing.

A 64-bit double is made by 52 bits of fraction and then exponent

That is why your binary string is long only 52 bits.

Further reading: http://en.wikipedia.org/wiki/Double_precision_floating-point_format

In order to get the first 64 bits, you might try a Maths library that performs multi-precision operations and get your result.

Don't worry. No -1 to your question, which is reasonable, but it shows you didn't study your homework :) (or you were asleep during class).

Bye.


Try BigDecimal - it has arbitrary precision for calculations.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号