B. Li
B. Li

Reputation: 1

C++ taylor series estimation of initial value differential equation accuracy

I was asked to use the taylor series method to estimate the initial value problem of x(t)'= tx(t) + t^4, x(5) = 3. I have to write code to display the estimates using the taylor series method by 0<=t<=5.

I have been taught to start at t=0, use initial condition at t=0 to find x0, and go up to t=5 by 0.01 increments by calculating x'', x''', etc and finding the next x corresponding to t+0.01.

How can I do this process backwards in c++ as in starting at t=5 and going increments down to 0 ?

Upvotes: 0

Views: 777

Answers (2)

skyking
skyking

Reputation: 14400

That's not a problem, what you need to concentrate on is the Taylor expansion of the solution, once you've done that it's only a matter of calculating the function for each value. To find the Taylor expansion you do it around t=5 since you know x(5)=3, then you find x'(5) directly from the differential equation, and subsequent derivatives by differentiating both sides of the equation repeatedly. You find that the t^4 term will eventually go away and the rest will result in a simple recursive formula.

#include <cstdio>

double c[] = { 3,
               625,
               500,
               300,
               120,
               24 };

double x(double t) 
{
    int j;
    double cc = 0;
    double cp = 0;
    double tj = 1;
    double s = 0;

    for(j=0; j<100; j++) {
        cc = (j-1)*cp + 5*cc;

        if( j < sizeof(c)/sizeof(c[0]) )
            cc += c[j];

        if( j > 0 )
            cc /= j;

        s += cc * tj;
        //printf("[%2d] %f %f\n", j, cc, s);

        tj *= (t-5);
    }

    return s;
}

int main()
{
    double t;

    for( t = 0.0; t<5.005; t+=0.01 )
        printf("%f %f\n", t, x(t));

    return 0;
}

The array c is terms that arise from the initial value and the derivatives of t^4. These terms vanish after 24. To loop 100 times have been found empirically since the expansion seem to have converged then.

Upvotes: 1

Ram&#243;n Esteve
Ram&#243;n Esteve

Reputation: 11

You can use a while loop like this:

double t = 5.0;
while (t > 0.0) {
       /* Your Code of Taylor function */
       t = t -0.01;
}

This code starts with a t value of 5.0 and decrements t in 0.01 in each iteration of the loop. The loop ends when t value reaches 0.0

Upvotes: 1

Related Questions