operators - BigDecimal Class in Java - Reason behind Constant values -


i working out java puzzlers second puzzle.

public class change {   public static void main(string args[]) {     system.out.println(2.00 - 1.10);   } } 

you think answer 0.9. not. if workout 0.8999999. solution given

system.out.println(new bigdecimal("2.00").subtract(new bigdecimal("1.10"))); 

now print 0.9. understood why prints 0.89999. while curiously debugging bigdecimal class, found there many constant values substituted in of places. i'll list below , interested know reason behind it.

bigdecimal.java line number 394,

               while (len > 10 && character.digit(c, 10) == 0) {                     offset++;                     c = in[offset];                     len--;                 } 

here character.digit(c,10).

public static int digit(char ch, int radix) {         return digit((int)ch, radix);     } 

here 10 passed radix.
q1. why 10 passed there.??

bigdecimal.java line number 732

int sign = ((valbits >> 63)==0 ? 1 : -1);         int exponent = (int) ((valbits >> 52) & 0x7ffl);         long significand = (exponent==0 ? (valbits & ((1l<<52) - 1)) << 1                             : (valbits & ((1l<<52) - 1)) | (1l<<52));         exponent -= 1075; 

q2. if code in depth, can understand valbits is, , unable understand why rightshift used where?

q3. here can see there many constants 63, 52 used. why?

q4. can understand hexadecimal 0x7ffl used here increase speed of execution. again why bitwise & operator used there hexadecimal constant.

i hope question clear. sincerely patience appreciated.

q1: of course, radix base of computation. you're using digit in base 10 ;)

q4: 7ff in binary: 0111 1111 1111

if read explanation of bit shift operators, java "bit shifting" tutorial? see >> 63 discard 63 first bits , keep last one. last bit sign bit (for signed types). if 1 integer negative, hence int sign there.

also, can refer https://en.wikipedia.org/wiki/floating_point definition of floating point. 52 distinguish between exponent , significand.

q4: of course, exponent, don't want use 'sign' bit in it, since it's not part of exponent, hence mask 7ff. bitwise & 0x7ff that; put 0 on first bit, , leave other same state. (see truth table of 'and' operator https://en.wikipedia.org/wiki/truth_table)

edit:

q4 complementary: if exponent example 12, first bit like:

0000 0000 1100 ... (positive value) (ex: 1x10^12) 1000 0000 1100 ... (negative value) (ex: -1x10^12) 

but: 1000 0000 1100 2060 decimal.

if apply 'mask':

  1000 0000 1100 & 0111 1111 1111 -> 0000 0000 1100 (12 decimal)   ,   0000 0000 1100 & 0111 1111 1111 -> 0000 0000 1100 (12 decimal) 

that's 0x7ff for.


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -