Rounding numbers in MATLAB

$\begingroup$

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

$\endgroup$ 3

1 Answer

$\begingroup$

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 format you can find ways to change this behavior.

Some interesting options:

format short % Default setting, 4 decimals
format long % Many decimals
format longG % Many decimals if available, won't show trailing zeros
$\endgroup$

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like