Mike Nelson
Mike Nelson

Reputation: 167

Variable value changes for no apparent reason

In my code I define a step size "h" before a while loop. Somehow it seems to change by itself when I try to use it in the loop. If I define it inside the loop it seems to be ok, but the data I get doesn't seem to be right so I'm guessing the problem might be related.

Even when I print it at this location (see the printf in the code) the output is 3 values and I have no idea why. If you see anything else that's not related but seems wrong please tell me, as I said I'm getting unexpected values (it may just be my formulas).

int main()
{
    FILE *f1;
    f1 = fopen("Question2 part 3 solution.txt", "w");
   double r0=0.05;
   double dr0=-a*a*r0/sqrt(1+pow(a*a*r0,2)),h=0.01;
   double k[4][3],x[]={dr0,z0,T0,r0},x1[]={0,0,0,0}, s=0;
   int i,j;

   while(s<=1)
    {
        //Runge-Kutta
        for (j=0;j<4;j++)
        {
            for (i=0;i<4;i++)
            {
                if (j==0){k[i][0]=h*System(i,x[0],x[1],x[2],x[3]);}
                if (j==1){k[i][1]=h*System(i,x[0]+k[0][0]/2.0,x[1]+k[1][0]/2.0,x[2]+k[2][0]/2.0,x[3]+k[3][0]/2.0);}
                if (j==2){k[i][2]=h*System(i,x[0]+k[0][1]/2.0,x[1]+k[1][1]/2.0,x[2]+k[2][1]/2.0,x[3]+k[3][1]/2.0);}
                if (j==3){k[i][3]=h*System(i,x[0]+k[0][2],x[1]+k[1][2],x[2]+k[2][2],x[3]+k[3][2]);}
            }
        }

        for (i=0;i<4;i++)
        {
            x[i]=x[i]+(k[i][0]+2.0*k[i][1]+2.0*k[i][2]+k[i][3])/6.0;
        }
printf("%8.3lf",h);
        s+=h;
    }

   fclose(f1);
    return(0);
}


double System(int i,double dr, double z, double T, double r)
    {
    //printf("%e\t%e\t%e\t%e\n",dr,z,T,r);
    if (T==T0 && z==z0 && i==0) {return  (-a*a*dr)*pow(1-dr*dr,3/2)/2.0;}
    if (i==0 && T!=0){return  (-a*a*r*(1-dr*dr)-dr*sqrt(1-dr*dr))/T;}
    if (i==1){return  (-sqrt(1-dr*dr));}
    if (i==2){return  (-a*a*r*dr+sqrt(1-dr*dr));}
    if (i==3){return  (dr);}
    //if (i==3){return  (-m2*l1*l2*B*theta1dt*theta2dt*sin(theta2-theta1)-l2*m2*g*B*sin(theta2));}
    }

Thanks in advance!

Upvotes: 1

Views: 926

Answers (2)

Edward Clements
Edward Clements

Reputation: 5132

You are overrunning the memory, variable k is defined as double k[4][3], but you are updating k[i][3]when j==3

Upvotes: 3

Some programmer dude
Some programmer dude

Reputation: 409176

See the declaration of k:

double k[4][3]

And then see this statement

k[i][3]=...

Here you write beyond the boundaries of the array, leading to undefined behavior.

Upvotes: 3

Related Questions