got stunned and cannot display on commond during using while-loop

7 ビュー (過去 30 日間)
david Chan
david Chan 2014 年 11 月 9 日
回答済み: Roger Stafford 2014 年 11 月 9 日
exp(x)= lim n to inf (1+x/n)^n
write a function to accept x and calculate on the right-­hand side for n = 1, 2, 3, … until the value changes by a fractional amount 0.0001.
I tried x=magic(6),but I got stunned and cannot display on commond window btw, can you guys check my code it good to run it?
x = magic(6);
y = exp(x);
n = 0;
intial = 10;
diff = 0.0001;
while (intial > diff)
n = n + 1;
myVal = (1 - x./n).^n;
intial = abs(myVal - y);
end
fprintf('The Value of e^-1 = %1.4f\n',y)
fprintf('My Value = %1.4f\n',myVal)
disp(['n = ' num2str(n)])

回答 (1 件)

Roger Stafford
Roger Stafford 2014 年 11 月 9 日
1. You used "(1-x./n).^n" instead of the required "(1+x/n)^n", so you can never hope to match elements of 'myVal' with those of 'y'.
2. Also you applied the condition "intial>diff" to your 'while' loop. As it stands, it would exit the first time any of the 36 elements of 'myVal' gets sufficiently close to the corresponding element of 'y'. You want it the other way around - it should exit only when ALL of them are sufficiently close. In other words you want "any(intial>diff)".

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by