How writing code sum 1+2+3+4+...+n
이전 댓글 표시
Hi. How I can writing code in MATLAB sum 1+2+3+4+..+n
and I can change ( n ) to any numbers and MATLAB can sum for me.
Thank you
답변 (2개)
Jos (10584)
2019년 5월 17일
or know your math classics ...
n = 120345428372
s = n*(n+1)/2
% sum(1:n) will fail!
댓글 수: 6
James Tursa
2019년 5월 17일
편집: James Tursa
2019년 5월 17일
Well, n*(n+1)/2 fails also ...
>> n = 120345428372;
>> fprintf("%20f\n",n*(n+1)/2)
7241511065080263868416.000000
>> vpa(n)*vpa(n+1)/2
ans =
7241511065080263999378.0
Jos (10584)
2019년 5월 18일
So true, James :-D
n = 120345428372;
sym(n) * (sym(n)+1) / 2
syms m
symsum(m, 1, n)
Alexander
2023년 12월 11일
Maybe a stupid question, but what is the right answer? 7241511065080263999378 or 7241511065080263868416?
v = sym('7241511065080263999378')
fprintf('%.999g\n', double(v))
So 7241511065080263868416 is the closest double precision representation of 7241511065080263999378
eps(double(v))
which is large enough adjacent representable double precision numbers in that range are 1048576 apart.
Alexander
2023년 12월 12일
Understood. Thank you
n = 4;
A = sum(1:n)
카테고리
도움말 센터 및 File Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!