In: Computer Science
The factorial of a non-negative integer is defined as follows: n! = 1 × 2 × ... × (n − 1) × n A. Write a function that takes an input value n and returns its factorial result n!. Ensure that your function returns an error statement if the input n is either a negative or a non-integer value. You cannot use the prod() or factorial() functions. The Euler number e is calculated as the sum of the infinite series shown in Eq. 1 below. Since we cannot actually approach infinity, we can assume a function fk to take the form shown in Eq. 2, and say that fk is related to e through Eq. 3. Eq. 1 Eq. 2 Eq. 3 e = ∑ 1 n! n→∞ n=0 fk = ∑ 1 n! n=k n=0 lim k→∞ fk = e Examples are provided below. We can see that when k is increased, the value of fk converges to a specific value (i.e. Euler's number) and the error decreases. The error here is defined as error = | approx−true true |, where approx refers to the approximation of Euler's number according to Eq. 2 above, and true value is taken to be MATLAB's Euler's number. f0 = 1 0! = 1 error = 0.6321 f1 = 1 0! + 1 1! = 2 error = 0.2642 f2 = 1 0! + 1 1! + 1 2! = 2.5 error = 0.0803 f3 = 1 0! + 1 1! + 1 2! + 1 3! = 2.6667 error = 0.0190 ... B. Determine the value of k in which the value of fk produces an error of less than 1e-10.
%Function for part a factorial_n.m
function nFact = factorial_n(n)
if n<0 || (floor(n)-n)~=0
error('Please enter a positive integer!')
else
nFact=1;
for i=1:n
nFact=nFact*i;
end
end
%script for part B
approx=1;
k=1;
while abs(approx-exp(1))>=1e-10
approx = approx + 1/factorial_n(k);
k=k+1;
end
fprintf('Value of k for which error is less than
1e-10:%d\n',k-1)
fprintf('Error: %.6e\n',abs(approx-exp(1)))
fprintf('Calculated value of fk: %.10f\n',approx)