Finite differences are usually used to integrate ODE's and PDE's. However, sometimes they can be used for differentiation which I illustrated simply by using the Matlab code below to differentiate the function $\cos(x)$. I am confused about when I can use finite differences for differentiation, and when I can't. I would like to ask for help to understand, because it may help me to solve a problem I am currently dealing with.
dx = 0.0001;
x = 0 : dx : 2 * pi;
y = zeros( 1, length(x) );
for i = 2 : length(x)
y(i) = ( cos( x(i) ) - cos( x(i - 1) ) ) / dx;
end
plot(x, y, 'b', 'linewidth', 2);
title('-sin(x) graph');
xlabel('x');
ylabel('y');
grid on
When I was learning how to use finite differences to solve the heat equation, I learned that the exact function $f(x,t)$ can be written as the sum of the numerically approximated function $F(x,t)$ and the error $E(x,t)$:
$$f(x,t) = F(x,t) + E(x,t) \tag 1$$
The stability condition will be satisfied if:
$$ \alpha{\Delta t \over \Delta x^2} < {1 \over 2} \tag 2$$
where $\alpha$ is the heat constant. The interpretation is the following, $\Delta t$ is less than one, so when the error is multiplied by it, it gets smaller. On the other hand, because $\Delta x$ is in the denominator and is also less than one, multiplication of the error with $1/ \Delta x$ causes the error to grow because $1/ \Delta x$ is greater than one. As a rule of thumb, keep the numerator small and the denominator big to achieve numerical stability.
However, in the code that I listed here, there is only $\Delta x$ in the denominator and there is no time step. I thought that doing differentiation this way was not possible because it would cause the error to grow. But that's not the case. I am guessing because the function is analytic and not numerically computed. Am I correct?
I am interested if I can actually solve a PDE using finite difference integration, and then calculate the first spatial derivative of that function using finite differences. Is this possible for the heat and wave equation? If it is, it would be easier for me to solve systems of partial differential equations.
In summary, I would like to know the following things:
- When can I use finite differences for numerical differentiation? Are there any specific conditions? How exactly does the step size affect the result?
- Can I use finite differences to calculate the first spatial derivative of a function after I calculated that function using finite difference integration (let's say the function satisfies the heat or wave equation for example)?