Find n for inverse of e approximation
20 ビュー (過去 30 日間)
古いコメントを表示
Victoria Gonzalez Canalle
2020 年 2 月 19 日
回答済み: Koushik Vemula
2020 年 3 月 3 日
Hi! I have to find an 'n' that approximates 1/exp(1) correctly to 0.0001, and then diplay which n that was.
% write code to compute the value of the inverse to within the tolerance:
inv = 1 / exp(1);
n = 1;
guess = (1-(1/n))^n;
while 0.0001 > abs(inv-guess)
n = n+1;
guess = (1-(1/n))^n;
end
% store the value of n needed to reach this accuracy:
accurate_n = n
But at the end,
accurate_n = 1 and I'm not sure why it is not treating it like a normal counter.
Anything helps!
2 件のコメント
Adam
2020 年 2 月 19 日
編集済み: Adam
2020 年 2 月 19 日
while 0.0001 > abs(inv-guess)
That effectively says, while the difference is very small carry on with the loop. I would imagine you want a < instead. Or, as I normally would, reverse the order of the operands to make it easier to understand!
In your case I'm guessing the condition fails first time so the loop is never executed.
These things are trivial to see using the debugger though.
Jacob Wood
2020 年 2 月 19 日
It looks like the only values n is able to take on is 1,2,3,4,...
Perhaps a bisection search, where you iteratively refine the value of n, would be a more appropriate solution?
This link might be helpful: https://ece.uwaterloo.ca/~dwharder/NumericalAnalysis/10RootFinding/bisection/matlab.html
採用された回答
Koushik Vemula
2020 年 3 月 3 日
According to what I understand, you are trying to get the value of ‘accurate_n’ which gives you a tolerance of ‘0.0001’. The problem is not in your approach but your condition in the while loop
while 0.0001 < abs(inv-guess)
Will give the expected answer which is ‘1840’
0 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!