3

Im running a simple script to estimate roots for a function. Everything works great, each iteration of the algorithm prints off the current x and f(x), but when the script finishes and sets the final estimate of x as the output of the function the value is returned and rounded to 3 decimal places...

while k < maxit
    k = k + 1;
    dx = b - a;
    xm = a + 0.5*dx;       %  Minimize roundoff in computing the midpoint

    fm = feval(fun, xm, diameter, roughness, reynolds);

    fprintf('%4d  %12.20e  %12.4e\n',k,xm,fm); 

    if (abs(fm)/fref < feps) | (abs(dx)/xref < xeps) % True when root is found
        r = xm;  
    return;
end

here is the tail bit of the output:

k       xm            fm
45  6.77444446476613980000e-003   1.3891e-012
46  6.77444446478035060000e-003  -1.3380e-011
47  6.77444446477324520000e-003  -5.9952e-012
48  6.77444446476969250000e-003  -2.3022e-012
49  6.77444446476791610000e-003  -4.5830e-013

    ans =

        0.0068

i dont know why its rounding the output.... how do i prevent that?

Amro
  • 123,847
  • 25
  • 243
  • 454
kbirk
  • 3,906
  • 7
  • 48
  • 72
  • just print the returned value the same way you did inside the function: `x = myRootsFunction(...); fprintf('%12.20e\n',x)` – Amro Oct 22 '11 at 21:03

2 Answers2

7

try typing 'format longE' in the command line before running the script

Andrew_L
  • 3,021
  • 2
  • 19
  • 18
  • or put it at the top of the script. It just changes how values are displayed in the command window - I believe if you were to use 'ans' in subsequent calculations, it uses it's full precision – Andrew_L Oct 22 '11 at 20:56
1

I had that problem too. Check out this page. It allows you to control the style of your outputs better.

http://www.mathworks.co.uk/help/techdoc/ref/format.html

Tetra
  • 747
  • 2
  • 9
  • 15