Eulers Number Code and Questions

3 ビュー (過去 30 日間)
DJ V
DJ V 2016 年 12 月 5 日
編集済み: Ramon Cajal 2017 年 1 月 28 日
My current code follows, but is in error when I enter "1" as the input. DO you see the problem?:
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
I'm trying to solve for the problem statement below:
Write a function called approximate_e that uses the following formula to compute e, Euler’s number:
Instead of going to infinity, the function stops at the smallest k for which the approximation differs from exp(1) (i.e., the value returned MATLAB’s built-in function) by no more than the positive scalar, delta, which is the only input argument. The first output of the function is the approximate value of e, while the second is k. (Note: if your program or the grader takes a long time, you may have created an infinite loop and need to hit Ctrl-C on your keyboard.) You are not allowed to use the built-in function factorial.

採用された回答

DJ V
DJ V 2016 年 12 月 5 日
Okay, solved it.
  1 件のコメント
Ramon Cajal
Ramon Cajal 2017 年 1 月 28 日
編集済み: Ramon Cajal 2017 年 1 月 28 日
I am struggling with this one. I'd appreciate understanding how did you get it right My code looks like:
function [e,k] = approximate_e( delta )
k= 0;
e = 0;
Bailout = 10000;
while abs(exp(1)-e) >delta
e =e+(1+(1/prod(1:k)));
k = k + 1;
if k > Bailout
break;
end
end

サインインしてコメントする。

その他の回答 (2 件)

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH 2016 年 12 月 5 日
You Can use this:
function [est,n ] = approximate_e( delta )
n=-1;
est=0;
while abs(exp(1)-est)>delta
n=n+1;
est=est+1/factorial(n);
end

DJ V
DJ V 2016 年 12 月 5 日
Can't use factorial.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by