got stunned and cannot display on commond during using while-loop
조회 수: 10 (최근 30일)
이전 댓글 표시
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)])
댓글 수: 0
답변 (1개)
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)".
댓글 수: 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!