I don't know if matlab is calculating this properly

조회 수: 1 (최근 30일)
Patrick Smith
Patrick Smith 2019년 9월 11일
댓글: Patrick Smith 2019년 9월 11일
Is this calculating correctly? It returns my answer as 1. It is meant to represent this series 1 + 1⁄r + 1⁄r^2 + 1⁄r^3 + … + 1⁄r^n.
function sum = mysum(r,n)
sum = 1;
for i = 1:n;
sum = sum + 1/(r^n);
end
Please help.

답변 (2개)

John D'Errico
John D'Errico 2019년 9월 11일
편집: John D'Errico 2019년 9월 11일
MATLAB is calculating what it calculated properly. The issue is, you told it to calculate the wrong thing. Computers are sooooo picky. :)
You don't tell us what values of r that you used. Or what n was when you ran this code. But if you used a large value for n, then yes, it SHOULD return 1. Or it might return inf. Really? What did you write, and why is that?
In fact, you wrote:
1 + 1⁄r^n + 1⁄r^n + 1⁄r^n + … + 1⁄r^n
Your exponent was fixed, at n.
The exponent in what you wrote was CONSTANT, at n. So if n was large, and abs(r ) was relatively large so that 1/abs(r ) is small, then you would see 1 as a result, because the powers will underflow. Or if r is itself small, then you would just get overflows.
The fix is easy, of course. Change n to i in the expression. That is, the exponent of r needs to be the index variable, not the number n itself.
function sum = mysum(r,n)
sum = 1;
for i = 1:n;
sum = sum + 1/(r^i);
end
And using the name sum for a variable is a really bad idea, as it will cause bugs in your code sometime, when you actually want to use the FUNCTION named sum.
Always avoid using existing function names as variable names.

madhan ravi
madhan ravi 2019년 9월 11일
편집: madhan ravi 2019년 9월 11일
Result = mysum(2,10) % just call it like this
doc function % to know how to use functions
function SUM = mysum(r,n)
SUM = 1; % don’t name variable sum because it will shadow the MATLAB’s inbuilt function
for ii = 1:n;
SUM = SUM + 1/(r^ii);
% ^^-- have a look here
end
end
  댓글 수: 11
madhan ravi
madhan ravi 2019년 9월 11일
function SUM = mysum(r,n)
SUM = 1;
for ii = 1:n;
SUM = SUM + 1/(r^ii);
% ^^-- have a look here
end
end
Patrick Smith
Patrick Smith 2019년 9월 11일
Perfectt! Thank you! I couldn't figure out why it kept giving me 1 which made not sense.

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

카테고리

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