Блог пользователя marcose18

Автор marcose18, 10 лет назад, По-английски

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 !.

  • Проголосовать: нравится
  • -17
  • Проголосовать: не нравится

»
10 лет назад, # |
Rev. 3   Проголосовать: нравится +3 Проголосовать: не нравится

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.

  • »
    »
    10 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    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 ?

    • »
      »
      »
      10 лет назад, # ^ |
        Проголосовать: нравится +3 Проголосовать: не нравится

      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.

      • »
        »
        »
        »
        10 лет назад, # ^ |
          Проголосовать: нравится 0 Проголосовать: не нравится

        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.