Asked by Patrick Smith
on 11 Sep 2019

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.

Answer by John D'Errico
on 11 Sep 2019

Edited by John D'Errico
on 11 Sep 2019

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.

Sign in to comment.

Answer by madhan ravi
on 11 Sep 2019

Edited by madhan ravi
on 11 Sep 2019

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

Patrick Smith
on 11 Sep 2019

I'm confused which n do I change to an i?

function sum = mysum(r,n)

sum = 1;

for i = 1:i;

sum = sum + 1/(r^n);

end

Do you mean this? or can you send back what you guys mean lol

madhan ravi
on 11 Sep 2019

function SUM = mysum(r,n)

SUM = 1;

for ii = 1:n;

SUM = SUM + 1/(r^ii);

% ^^-- have a look here

end

end

Patrick Smith
on 11 Sep 2019

Perfectt! Thank you! I couldn't figure out why it kept giving me 1 which made not sense.

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.