Reputation: 9
While I was coding in C++ I stumbled upon something, the return value of log2(n)
and log2l(n)
are completely different for a certain value of n
:
#include<bits/stdc++.h>
using namespace std;
int main(){
int d= log2l(288230376151711743);
cout<<d;
return 0;
}
This above code displays a value of 57 whereas the following code:
#include<bits/stdc++.h>
using namespace std;
int main(){
int d= log2(288230376151711743);
cout<<d;
return 0;
}
Displays a value of 58
upon execution.
Why is this occurring can someone please explain me ?
Upvotes: 0
Views: 219
Reputation: 7726
Try using the following expression for do-it-yourself:
auto log2 = log2(288230376151711743); // log2 => double | log2l() => long double
You'll get to know that variable d
is a datatype set to double
, again if you do the same thing with log2l()
, you'll find that d
is set to long double
, i.e. the function log2l()
returns a long double
, but the value is rounding down while typecasting implicitly from a long double
into int
.
That's why, it'll show 58
for log2()
. And in contrary, 57
for log2l()
when the variable is an integer.
Upvotes: 1
Reputation: 557
It's because you are typecasting double to integer datatype which is rounding it down.
#include <bits/stdc++.h>
using namespace std;
int main() {
cout << log2(288230376151711743) << "\n";
cout << log2l(288230376151711743) << "\n";
cout << (int) log2(288230376151711743) << "\n";
cout << (int) log2l(288230376151711743) << "\n";
cout << (long) log2(288230376151711743) << "\n";
cout << (long) log2l(288230376151711743) << "\n";
cout << (double) log2(288230376151711743) << "\n";
cout << (double) log2l(288230376151711743) << "\n";
return 0;
}
try to run this code and observe the results. log2 docs
Upvotes: 1