Search code examples
c++logarithm

getting wrong answer by logarithm in c++


Well i was creating a program in c++ .Then i noticed that there were some error due to which my program was not functioning correctly

compiler used:- Dev c++

Error was this:-

Suppose n1=274877906944 which is 2^38. so log(n1) should be 38 which is correct. now let n2=274877906942 which is smaller than n1.

So that means if we calculate log(n2) then it must give me less than log(n1).But log(n2) gave me the same result as log(n1) which is 38. Which is wrong!!!

Someone please explain this stuff..


Solution

  • You see the result that you do because of rounding. If you increase your precision, it'll be okay (note that the log2 function in <cmath> will cast your integers to double):

    std::cout << std::fixed;
    std::cout << std::setprecision(16);
    std::cout << static_cast<double>(274877906944) << std::endl;
    std::cout << static_cast<double>(274877906942) << std::endl;
    std::cout << static_cast<double>(274877906948) << std::endl;
    
    std::cout << log2(274877906944) << std::endl;
    std::cout << log2(274877906942)  << std::endl;
    std::cout<<  log2(274877906948) << std::endl;
    

    Produces:

    274877906944.0000000000000000
    274877906942.0000000000000000
    274877906948.0000000000000000
    38.0000000000000000
    37.9999999999895053
    38.0000000000209965

    Demo