I don't know if matlab is calculating this properly

5 Ansichten (letzte 30 Tage)
Patrick Smith
Patrick Smith am 11 Sep. 2019
Kommentiert: Patrick Smith am 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.

Antworten (2)

John D'Errico
John D'Errico am 11 Sep. 2019
Bearbeitet: John D'Errico am 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.

madhan ravi
madhan ravi am 11 Sep. 2019
Bearbeitet: madhan ravi am 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
  11 Kommentare
madhan ravi
madhan ravi am 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
Patrick Smith am 11 Sep. 2019
Perfectt! Thank you! I couldn't figure out why it kept giving me 1 which made not sense.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by