marcose18's blog

By marcose18, 9 years ago, In English

Hello Codeforces community ! Suppose I have declared a variable long cnt=0; //then I wish to do cnt+=Math.pow(2,59); //And again I do cnt+=Math.pow(2,3); Ideally now value should be cnt + 8 but value output by compiler is still cnt i.e. 8 is notincremented but if I parse that second statement somewhat like cnt+=(long)Math.pow(2,3); I am getting the desired answer .Would someone mind explaining it what'sthe difference here! Any help will be appreciated ! Thanx !.

  • Vote: I like it
  • -17
  • Vote: I do not like it

| Write comment?
»
9 years ago, # |
Rev. 3   Vote: I like it +3 Vote: I do not like it

You might want to read http://en.wikipedia.org/wiki/Double-precision_floating-point_format for more information about doubles.

But I would say if you don't cast Math.pow(2, 3) which is double, to long, adding will be performed on doubles and 8 is too small compared to 2^59 and will be lost because there is only space for 53 significant digits. On the other hand, if you cast operation will be 2^59 + 8 on longs which is obviously fine.

You might ask why then 2^59 is perfectly stored and was converted from double to long, but has more than 53 bits, the thing is that it has only one significant digit and exponent set to 59. Someone correct me if I'm mistaken.

  • »
    »
    9 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Why adding would be performed in doubles as cnt is a long variable type and after first assignment it's alike adding a double to a long .Don't you think ?

    • »
      »
      »
      9 years ago, # ^ |
        Vote: I like it +3 Vote: I do not like it

      well cnt += Math.pow(2, 3) is the same as cnt = cnt + Math.pow(2, 3) and as you know if one of the operands is double other one will be casted to double.

      • »
        »
        »
        »
        9 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        to be precise cnt = cnt + Math.pow(2, 3) will probably not work because you assign double to long.

        cnt += Math.pow(2, 3) is equivalent to cnt = (long)(cnt + Math.pow(2, 3)) and you main point that two doubles are adding still true.