Can anyone find the error in my code?

1 回表示 (過去 30 日間)
Georgia potter
Georgia potter 2017 年 5 月 21 日
回答済み: Srishti Saha 2018 年 5 月 1 日
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.
function [e, k] = approximate_e( delta )
k= 0;
e = 0;
while ((exp(1))-e) > delta
k = k + 1;
e = e + 1/prod(1:k);
if k > 1000
break;
end
end
note: this code fails to produce the correct output for delta = 1
YOU CAN'T USE THE FACTORIAL FUNCTION
  2 件のコメント
Akira Agata
Akira Agata 2017 年 5 月 22 日
Let me clarify.
Using the Taylor expansion, exp(1) can be expanded as follows:
exp(1) = 1 + (1/1) + (1/2!) + (1/3!) + ...
On the other hand, your code calculates following equation.
(1/1) + (1/2!) + (1/3!) + ...
So, I think the code correctly generates ~1.718.
Steven Liu
Steven Liu 2017 年 6 月 4 日
e should be 1, not 0. Problem solved!

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

回答 (1 件)

Srishti Saha
Srishti Saha 2018 年 5 月 1 日
Hey, this piece of code works just fine:
%function to compute euler's number
function [approx_e, k] = approximate_e (delta)
% Set the variables for the while loop.
k = 0;
fact = 1;
approx_e=1;
while abs(approx_e - exp(1)) > delta
k=k+1;
fact = fact * (1/k);
approx_e = approx_e + fact;
end
approx_e;
k;
end

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by