2016-12-05 130 views
-2
function [est k ] = approximate_e(delta) 
%APPROXIMATE_E Summary of this function goes here 
% Detailed explanation goes here 
n =1; 
est = 0; 
while abs(exp(1)-est)>delta 
    if n ==1 
     est = 1; 
    end 
    if n == 2 
     est = 2; 
    end 
    if n >2 
     est = est+1/prod(1:(n-1)); 
    end 
    fprintf "e is %d and n is %d: \n",est,n 
    k = n; 
    n = n + 1; 
    if n >10000 
     fprinf "n is greater than 10000.\n" 
     break; 
    end 
end 

我写了上面的代码,试图回答涉及欧拉数的计算问题。问题如下:Matlab需要的解决方案

编写一个名为approximate_e使用下列公式 函数计算e,欧拉数:

enter image description here

,而不是去到无穷大,功能停止在最小k,近似值与exp(1)不同(即,

value returned MATLAB's bui lt-in函数)不超过正数标量delta,这是唯一的输入参数。函数的第一个 输出是e的近似值,而第二个 是k。 (注意:如果您的程序或平地机需要很长时间,您可能会在 键盘上创建无限循环并需要按Ctrl-C。)您不允许使用内置函数阶乘。

+4

问题在哪里? – obchardon

+0

那么你的代码是什么意外的(除了'fprintf's)呢? – beaker

回答

0
function [est] = approximate_e(delta) 
%APPROXIMATE_E Summary of this function goes here 
% Detailed explanation goes here 
n = 0; 
est = 0; 
TerminationCondition = 10000; 
while abs(exp(1)-est)>delta 
    est = 1/factorial(n)+est; 
    display(['The current value of est is ', num2str(est),char(10)]); 
    n = n + 1; 
    if n > TerminationCondition 
     break; 
    end 
end 
if n > TerminationCondition 
    display(['n is greater than ', num2str(TerminationCondition), ' terminating loop']); 
else 
    display(['This estimation took ', num2str(n), ' cycles to complete']); 
end 

你必须调整功能,让您的K值(这是变量n)。