got stunned and cannot display on commond during using while-loop
10 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (1)
Roger Stafford
el 9 de Nov. de 2014
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 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!