Euler's method approximation

605 Views Asked by At

I'm supposed to write a program for approximating the value of function $y = y(x)$, which is given as: $$y' = \frac{1+y}{1 + x^2}$$ I also know that $y(0) = 0$. I should approximate the value for $x=2$.

Solving the differential equation gets me that $y = Ke^{\arctan(x)} -1$, where $K\in\mathbb{R}^+$
So I can get the value of $K$ by solving $0 = Ke^{\arctan(0)} - 1$. Therefore $K = 1$.

But I'm not sure if the approximation should use the function in the original shape or the result of the differential equation.

If I use $y = e^{\arctan(x)} - 1$ for the aprroximation, the results are ($h$ is the size of step):
For $h=1$ it is $2.0$
For $h=0.5$ it is $2,02885...$
For $h=0.25$ it is $2,03366...$

The precise value is $y(2) = e^{\arctan(2)} - 1 = 2.0257189050$

Code used to calculate the results:

DWORD ApproximateExampleOne(){
    double stepSize = 0.0;
    double result = 0.0;
    double iterator = 0.0;
    double preciseValue = exp(atan(2.0)) - 1;

    fflush(stdin);
    _tprintf(_T("Approximating equation [y = e^(arctan(x)) - 1] for x = 2 by Euler's method\n\n"));
    _tprintf(_T("Please enter size of the step [#.#]: "));
    _tscanf(_T("%lf"), &stepSize);

    if(stepSize <= 0){
        _tprintf(_T("Size of the step can't be zero or negative! Aborting... \n"));
        return ERROR_INVALID_PARAMETER;
    }

    for(iterator = stepSize; iterator < 2.0; iterator += stepSize){
        result = result + stepSize*(exp(atan(iterator)) - 1);
    }

    _tprintf(_T("\nPrecise result is: %.10f\n"), preciseValue);
    _tprintf(_T("Approximate result is: %.10f\n"), result);
    _tprintf(_T("Approximation error is: %2.0f%%"), (fabs(preciseValue - result)/fabs(preciseValue))*100);

    return ERROR_SUCCESS;
}
1

There are 1 best solutions below

1
On BEST ANSWER

See, when you're using Euler's method, the assumption there is that you're unable or unwilling to find a symbolic solution to your differential equation, and you just want to estimate the function values of a solution at a few points.

Remember that Euler's method for $y^\prime=f(x,y)$ takes the form

$$\begin{align*}x_{k+1}&=x_k+h\\y_{k+1}&=y_k+hf(x_k,y_k)\end{align*}$$

where $h$ is a predetermined stepsize and $x_0,y_0$ correspond to your initial conditions.

That's what you need to do here: pick a stepsize $h$, let $x_0=y_0=0$ (due to your initial conditions), and then keep running Euler (replacing $f(x,y)$ with whatever's equated to the derivative) up until $x_{k+1}=2$. The corresponding value of $y_{k+1}$ is the Euler estimate, which I presume you'll be asked to compare with the exact solution in this case...