-5

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

Nishant sharma
  • 116
  • 1
  • 11
  • 6
    If you you show us your code, we can help you better. – Bart Friederichs Jan 05 '17 at 13:32
  • 2
    [`log2`](http://en.cppreference.com/w/cpp/numeric/math/log2) returns a `float` or `double` - so how are you getting an integer? – UnholySheep Jan 05 '17 at 13:33
  • #include #include using namespace std; int main() { long double n; cin>>n; cout< – Nishant sharma Jan 05 '17 at 13:35
  • 1
    The argument is cast to a double, and with floating point math being what it is, I think all those values are close enough to approximate an answer as "38" – AndyG Jan 05 '17 at 13:37
  • Given the size of the values and the precision of floating point representation, the results look pretty good to me. Have a look at an [online logarithm calculator](http://www.rapidtables.com/calc/math/Log_Calculator.htm) and compare. – Evil Dog Pie Jan 05 '17 at 13:38

1 Answers1

2

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

AndyG
  • 39,700
  • 8
  • 109
  • 143
  • so i need to only type cast it into the double.That will do the job? or i just take the value in double will it work? – Nishant sharma Jan 05 '17 at 13:42
  • 2
    `log2` is already returning a `double`. Store that result in a `double`, and to display it properly you'll need to increase the number of significant figures to be printed, as I've shown. – AndyG Jan 05 '17 at 13:43