Search code examples
c++cmodeling

Population growth model not corresponding to expectations


I'm trying to make a bacteria model just for fun, and i'm using the pow(a, b) function as a function to calculate the growth of the population. When the bacteria population hits the maximum amount of food units that it's environment can provide, it declines by 70%, as a result of competition between the individuals. I'm saving the results to a txt so I can plot it later. The problem I'm having is that the population oscillates correctly until I reach a number of reproduction cycles arount t = 900, then the population just defaults to 0. The code follows bellow, I hope you don't mind the name of variables and functions written Portuguese.

bool
check_aliemento (unsigned long int *pop)
{
    if (*pop >= MAX_ALIMENTO) return false;
    return true;
}

unsigned long int
replicaBacteria (unsigned long int *popInit, unsigned int tempo_t, double taxa)
{
    unsigned long int nextPop = round ((*popInit) * 
                static_cast<double> (pow (1 + taxa, tempo_t))); 
                //I'm almost sure that the problem happens in this pow() function
    while (! check_aliemento (&nextPop))
    {
        nextPop = (0.7 * nextPop);
    }
    return nextPop;
}



   int
main ( int argc, char** argv )
{
    unsigned long int a = 2;
    ofstream myfile;
    myfile.open ( "C:\\Users\\Pedro\\Desktop\\values.txt" );
    for ( unsigned int i; i < 1000; i ++ )
    {
        unsigned long int pop = replicaBacteria ( &a, i, 0.05 );
        myfile << pop << " ==> time = " << i;
        myfile << "\r\n";
    }
    myfile.close ( );
    return 0;
}

Sample output:

8080 ==> time = 872
8484 ==> time = 873
8909 ==> time = 874
9354 ==> time = 875
9822 ==> time = 876
7219 ==> time = 877
7580 ==> time = 878
7958 ==> time = 879
8357 ==> time = 880
8775 ==> time = 881
9214 ==> time = 882
9675 ==> time = 883
7110 ==> time = 884
7466 ==> time = 885
7839 ==> time = 886
8232 ==> time = 887
8643 ==> time = 888
9075 ==> time = 889
9529 ==> time = 890
7003 ==> time = 891
7354 ==> time = 892
7721 ==> time = 893
8108 ==> time = 894
8513 ==> time = 895
0 ==> time = 896
0 ==> time = 897
0 ==> time = 898
0 ==> time = 899
0 ==> time = 900

Solution

  • pow (1 + taxa, tempo_t)
    

    Obviously long int can't hold 2^900 so what you are seeing here is integer overflow use a data-type which can hold large values like

    unsigned long long