This piece of code is taken from a bigger code, where it was creating a problem. I am able to reproduce the same error here.
The code requires unsigned long long integers to deal with large values. The requirement is to convert a given binary number (stored in a vector) to a decimal number (unsigned long long). It is supposed to be a simple code. But it turns out the function configuration_to_int_1
produces wrong result for some binary numbers. If you run the code, you will see that in the very last step of the loop, it adds an even and an odd number to give an even output, which is bizarre!! After spending an entire day to understand the root of this problem, I rewrote the function as configuration_to_int_2
where I have just stored the value of pow(2,i)
in a long long integer at the beginning and used this variable whenever pow(2,i)
was required. This gives me the correct value!!
Can anyone explain to me, what was going wrong in the first case? Thanks in advance. Here is the code:
#include <stdio.h>
#include <bitset>
#include <vector>
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
unsigned long long hash=9007199256641537;
int NLL, Nphi;
NLL=3;
Nphi=18;
vector<unsigned short int> basis(3*Nphi,0);
unsigned long long int configuration_to_int_1(vector<unsigned short int> conf, int NLL, int Nphi);
unsigned long long int configuration_to_int_2(vector<unsigned short int> conf, int NLL, int Nphi);
void int_to_occupation(unsigned long long int num, int Nphi, int NLL, vector<unsigned short int>& occupation);
int_to_occupation(hash, Nphi, NLL, basis);
configuration_to_int_1(basis, NLL, Nphi);
configuration_to_int_2(basis, NLL, Nphi);
return 0;
}
void int_to_occupation(unsigned long long int num, int Nphi, int NLL, vector<unsigned short int>& occupation)
{
bitset<64> bb(num);
for (int r = 0; r < NLL*Nphi; ++r)
{
occupation[r] = bb[r];
}
}
unsigned long long int configuration_to_int_1(vector<unsigned short int> conf, int NLL, int Nphi)
{
unsigned long long int x=0;
for(int i=0;i< NLL*Nphi;i++)
{
if (conf[i]==1)
{
cout<<x<<" + "<<pow(2,i)<<" = ";
x=x+pow(2,i);
cout<<x<<endl;
}
}
return x;
}
unsigned long long int configuration_to_int_2(vector<unsigned short int> conf, int NLL, int Nphi)
{
unsigned long long int x=0,c;
for(int i=0;i< NLL*Nphi;i++)
{
if (conf[i]==1)
{
c=pow(2,i);
cout<<x<<" + "<<c<<" = ";
x=x+c;
cout<<x<<endl;
}
}
return x;
}