Matlab/Octave finty

From RoboWiki
Revision as of 15:24, 25 February 2012 by Balogh (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Niektoré zaujímavé konštrukcie a postupy

How to find square root of 2 in 15 significant figures

octave:1> format long
octave:2> sqrt(2)
ans =  1.41421356237310

Alebo iný postup

   x = 1.5;
   x = (x + 2/x) / 2;
   x = (x + 2/x) / 2;
   x = (x + 2/x) / 2;
   x = (x + 2/x) / 2;
   fprintf('%18.15f\n', x)

Este iny postup

printf ("%.15f\n", sqrt(2));
produces
1.414213562373095

With

  function x = approxroot2(n)
     x = 2;
     while n
         printf ("%.15f\n", x - 1);
         x = 2 + 1/x;
         n--;
     endwhile
     x -= 1;
     printf ("%.15f\n", x);
  endfunction
approxroot2(25);
produces
1.000000000000000
1.500000000000000
1.400000000000000
1.416666666666667
1.413793103448276
1.414285714285714
1.414201183431953
1.414215686274510
1.414213197969543
1.414213624894870
1.414213551646055
1.414213564213564
1.414213562057320
1.414213562427273
1.414213562363800
1.414213562374690
1.414213562372821
1.414213562373142
1.414213562373087
1.414213562373096
1.414213562373095
1.414213562373095
1.414213562373095
1.414213562373095
1.414213562373095
1.414213562373095 


How do I evaluate <math> 1^2 + 2^2 +3^2 + \dots +100^2</math>

sumsq(1:100)
a=1:100;
b=a.^2;
c=sum(b)
s = 0;
 for i = 1:100,
  s = s + i^2;
 endfor

or you could vectorize the loop and get:

s = sum((1:100).^2);

Or

(1:100)*(1:100)'

Or

100*101*201/6

because

<math>\sum n^2 = \frac{n(n+1)(2*n+1)}{6}</math>

Or

norm(1:100)^2

This will also work

100*var(-100:100)