vector elements and exponential
15 次查看(过去 30 天)
显示 更早的评论
Show that lim n -->inf (1+1/n)^n=e
Do this by first creating a vector n that has the elements: 1 10 100 500 1000 2000 4000 and 8000. Then, create a new vector y in which each element is determined from the elements of n by (1+1/n)^n
Compare the elements of y with the value of e (type exp(1) to obtain the value of e)
I have done
n = [1 10 100 500 1000 2000 4000 8000]
and using the formula
y=(1 + (1./n)).^n
exp(1)
fprintf('the value of y is %6.3f while exp(1) is %8.3f\n'y,exp(1))
for some reason when I do fprintf the value that it gives are different to the values obtained in "y"
回答(1 个)
Walter Roberson
2013-2-20
Because your "n" is a vector, your "y" is a vector, but your "fprintf" is designed for scalar y and scalar exp(1).
When you use fprintf, each numeric item is used for the next available format code, and at the end of the format string, fprintf goes back and starts from the beginning of the format string again. Thus if you had
A = 1:3;
fprintf('A = %f, B = %g\n', A, exp(1))
then A(1) would be matched against the %f, A(2) would be matched against the %g, then the format string would be reused again so A(3) would be matched against the %f, and then since A was finished, exp(1) would be matched on the next format code, the %g. Result:
A = 1, B = 2
A = 3, B = 2.71
Any individual format code such as %f is not re-used "in place" until a vector is finished. You would not get
A = 1 2 3, B = 2.71
To get that effect, you would use:
fprintf('A =')
fprintf(' %f', y)
fprintf(', B = %g\n', exp(1))
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!