I don't know if matlab is calculating this properly
1 回表示 (過去 30 日間)
古いコメントを表示
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.
0 件のコメント
回答 (2 件)
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.
0 件のコメント
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
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
参考
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!