I am making a function for finding the approximate value of the second derivative (using the forward difference formula) of $sin(x)$ in $x=\frac {\pi}{3}$ with step $h=10^{-n}$ for $n=1, 2, 3, 4, 5$
The problem is that MATLAB rounds all the results by 4 positions after the decimal which makes all approximations equal. How can I fix this?
Here is the code:
function [ D2h ] = Forward( n )
D2h=zeros(n,1);
x=pi;
for i=1:n
h=10^-i;
D2h(i,1)=(sin(x+2*h)-2*sin(x+h)+sin(x))/h^2;
end
Something that many people run into is that by default, matlab only displays 4 decimals. Of course, the precision is not lost, it is just not shown.
If you try
help formatyou can find ways to change this behavior.Some interesting options: