Question

New to matlab and I cannot understand a bit of code I have been given:

x = 1; % initial guess = 1 
Tol = 5e-9; % correct to 8 decimal places 
count = 0; 
f=0.54030231; % f(1)= 0.54030231 
fprintf('step x f(x)\n') 
fprintf('---- ----------- ----------\n') 
fprintf('%1i %12.8f %12.8f\n',count,x,f) 
while abs(f)>Tol %loop until the absolute value of f is smaller than tolerance
count = count + 1 
deriv = -sin(x); ; % first derivative of f(x) 
x2 = x - (f/deriv); % new value of x 
x = x2; 
f = cos (x); % new value of f(x) 
fprintf('%3i %12.8f %12.8f\n',count,x,f) 
end

The program is newtons method for finding roots of equations which I understand.

What I don't understand is this part:

fprintf('---- ----------- ----------\n') 
fprintf('%1i %12.8f %12.8f\n',count,x,f) 

Questions:

  1. Why is the last bit of the second line divided by n?
  2. What are the numbers in the second line i.e. %1i, %12.8f etc?
  3. How does this work with the 'count, x, f' that is written after it?

Thanks

Was it helpful?

Solution

\n is a newline character.

For the rest, you're looking at Matab's version of printf format strings. With slight variations these are used in dozens of languages. Count, x, and f are inserted at the % 1i is a integer with 1 digit, 12.8f is a floating point number with 12 characters, 8 after the decimal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top