2016-12-05 141 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)。