Matlab/Octave finty

From RoboWiki
Revision as of 09:05, 22 February 2012 by Balogh (talk | contribs)
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)


How do I evaluate 1^2 + 2^2 +3^2 +...+100^2

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 (sum(n^2)) = n*(n+1)*(2*n+1)/6)

Or

norm(1:100)^2

This will also work

100*var(-100:100)