How to save each term from a sum

4 次查看(过去 30 天)
Phoenix Love
Phoenix Love 2020-2-24
评论: Lourval 2024-2-6
clear
n = input('Number of terms: ');
terms = 0;
for n = 1:n
terms=terms + (sum(1/(n^2)));
end
pi1=sqrt(6*terms);
fprintf('the estimate for pi is %g.\n',pi1);
errorF = ((pi1-pi)/pi)*100;
fprintf('the percentage error is %g.\n',errorF);
Hi so I am relatively new to matlab and im trying to use Uelers formula to calculate pi. i am trying to save each term. I am unsure how to do this and spent a long time already trying to figure it out.

回答(2 个)

the cyclist
the cyclist 2020-2-24
编辑:the cyclist 2020-2-24
clear
n = input('Number of terms: ');
terms = zeros(n,1);
for ni = 1:n
terms(ni)=terms(ni) + (sum(1/(ni^2)));
end
pi1=sqrt(6*terms);
fprintf('the estimate for pi is %g.\n',pi1);
errorF = ((pi1-pi)/pi)*100;
fprintf('the percentage error is %g.\n',errorF);
I did a few things here. The main one is that I made your variable terms into a vector, instead of a scalar.
Then, in each iteration of the loop, I write into one element of the vector, rather than overwriting the scalar over and over. (Note that I preallocated the memory for terms.)
Another small thing I did was change your looping variable to ni. It's confusing to have your looping variable named the same as an already existing variable in the workspace. What if you had wanted to refer to both?

Giuseppe Inghilterra
Hi,
try to run this code. I add a plot in which I show how "pi1" converges toward to pi value.
clear
n = input('Number of terms: ');
terms = zeros(n,1);
for ii = 2:n
terms(ii,1) = terms(ii-1,1) + 1/(ii-1)^2;
end
pi1=sqrt(6*terms);
plot(1:n,pi1,'-.')
hold on
plot(1:n, pi*ones(n,1))
fprintf('the estimate for pi is %g.\n',pi1(end));
errorF = ((pi1(end)-pi)/pi)*100;
fprintf('the percentage error is %g.\n',errorF);
I did some changes:
  • terms is a vector, not a scalar;
  • ii is loop variable, instead of n;
  • add plot functions.
  • (sum(1/(n^2))) becomes 1/(ii-1)^2 because n is a scalar not a vector, you don't need sum function.
You can add title, xlabel, ylabel to plot in order to make it more attractive.
  2 个评论
Lourval
Lourval 2024-2-3
Hello Giuseppe! How could I do that if i have an expression with two variables, k and t, such as:
f(t)=(cos((2*k+1)*pi*t)/(2*k+1)^2 , t from 0 to m and k from 0 to n
and the objective is to plot f(t)
Lourval
Lourval 2024-2-6
Well, by trial and error i have found the solution:
clear
m = input('Number of tterms: ');
n = input('Number of kterms: ');
tterms = zeros(m,1);
kterms = zeros(n,1);
for t = 2:m
for k = 2:n
kterms(k,1)=kterms(k-1,1)+(cos((2*(k-2)+1)*(99/3240)*pi*t))/(2*(k-2)+1)^2;
end
tterms(t,1)=tterms(t,1)+kterms(k,1);
end
ang=90-720/(pi^2)*tterms
plot(1:n,ang,'-.')

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Weather and Atmospheric Science 的更多信息

产品


版本

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by