Approximating Euler's sum using while loop

조회 수: 7 (최근 30일)
Eric
Eric 2014년 11월 9일
댓글: Eric 2014년 11월 11일
So I have been working on this code that will approximate the Euler's approximation to within .01% of the actual value. It seems that I may be missing something, when the function runs it will only print the 3 terms, and will print .36111--- for almost any number. The actual value that I am trying to approximate is pi^2/6. Could anybody take a look at what I am missing
function ApproxEulers(PercError,exact)
i=1;
sum=0;
Error = 100;
while Error >= PercError ;
i=i+1;
sum = sum + (1/(i^2));
Error = Error -(100*abs((exact - sum)/exact));
end
fprintf('The number of terms: %d \n', i)
fprintf('The approxamite value: %.8f \n', sum)
fprintf('The exact value: %.8f \n', exact)
end

채택된 답변

Orion
Orion 2014년 11월 9일
편집: Orion 2014년 11월 9일
the line
Error = Error -(100*abs((exact - sum)/exact));
is wrong.
Replace it with
Error = 100*abs((exact - sum)/exact);
also you initialize i to 1, should be 0.
In the end :
function ApproxEulers(PercError,exact)
i=0;
sum=0;
Error = 100;
while Error >= PercError ;
i=i+1;
sum = sum + (1/(i^2));
Error = 100*abs((exact - sum)/exact);
end
fprintf('\n\tThe number of terms: %d \n', i)
fprintf('\tThe approxamite value: %.8f \n', sum)
fprintf('\tThe exact value: %.8f \n\n', exact)
end
which will give you
>> ApproxEulers(.001,pi^2/6)
The number of terms: 60793
The approxamite value: 1.64491762
The exact value: 1.64493407
One remark : sum and error are the names of basic matlab functions. try to not use them when you code. Just pick other names to define your variables, otherwise, one day you're gonne struggle to debug a code because of that kind of mistake.

추가 답변 (1개)

Eric
Eric 2014년 11월 10일
Ok thank you for that, I do want to know why the 'i' is to start at zero instead of one. The matlab book mentioned that any thing that involves multiplication or division should use a 1, I understand that we are summing up the products but it didn't make much sense to start with zero when I first wrote the code.
  댓글 수: 2
Orion
Orion 2014년 11월 10일
The initialization depends on "where" you will increase your variable.
Here, at the first iteration, i becomes 1, which will give you the first element of your sum.
1/1² + 1/2² + ...
in your original code, you were calculating :
1/2² + 1/3² + ... => miss 1, you were calculating "pi^2/6 - 1"
you can change the initialization to 1, but then the increase of i must be at the end of the while loop instead of the beginning.
Eric
Eric 2014년 11월 11일
Makes much more sense now, thank you again for the assistance!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by