Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

java - How can a float64 store more than 64 bits?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Java, 1 << 100 is 16, because 1 is a 32-bit int value, so only the lower 5 bit of 100 is used.

100 = 0x64 => 0x04, and 1 << 4 = 16.

If you want full 101 bit precision, use BigInteger and BigDecimal for the calculations:

BigInteger bigInt = BigInteger.ONE.shiftLeft(100); 
BigDecimal bigDec = new BigDecimal(bigInt).multiply(BigDecimal.valueOf(0.1));
double d = bigDec.doubleValue();
System.out.println("bigInt = " + bigInt);
System.out.println("bigDec = " + bigDec);
System.out.println("d = " + d);

Output

bigInt = 1267650600228229401496703205376
bigDec = 126765060022822940149670320537.6
d = 1.2676506002282295E29

Or maybe you don't use BigDecimal:

BigInteger bigInt = BigInteger.ONE.shiftLeft(100); 
double d = bigInt.doubleValue() * 0.1;
System.out.println("bigInt = " + bigInt);
System.out.println("d = " + d);

Output

bigInt = 1267650600228229401496703205376
d = 1.2676506002282295E29

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...