Difference between revisions of "Matlab/Octave finty"
From RoboWiki
Line 17: | Line 17: | ||
− | '''How do I evaluate | + | '''How do I evaluate <math> 1^2 + 2^2 +3^2 + \dots +100^2</math>''' |
sumsq(1:100) | sumsq(1:100) | ||
Line 40: | Line 40: | ||
Or | Or | ||
100*101*201/6 | 100*101*201/6 | ||
− | because | + | |
+ | because | ||
+ | |||
+ | <math>\sum n^2 = \frac{n(n+1)(2*n+1)}{6}</math> | ||
Or | Or |
Revision as of 09:18, 22 February 2012
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 <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)