How to use an anonymous function to solve Stirling series n! using MATLAB

$\begingroup$

I want to be able to use Stirling Series to approximate n! inputing a vector. So far, I can do this entry wise. And I'm not sure why I cannot input a vector.

F = @(n) sqrt(2.*pi.*n).*(n/exp(1)).^n .* (12.*n+1)/(12.*n)
>> F(1), F(2), F(3), F(4)
ans = 0.998981759637105
ans = 1.998962866134357
ans = 5.998326524438801
ans = 23.995887114828559

When I try

n = [1:6]
F(n)
n = 1 2 3 4 5 6
ans = 3.226859511810607e+02

I would like to get the solution of

F(n)
ans =
0.9990 1.9990 5.9983 23.9959 119.9862 719.9404

Can someone offer some advice?

$\endgroup$

1 Answer

$\begingroup$

You are not using right array division. Using "/" instead of "./" yields to a single scalar.

Change your function handle to

F = @(n) sqrt(2.pi.n).(n./exp(1)).^n . (12.*n+1)./(12.*n)

For the input

n=[1:6]

we then get

ans = 0.9990 1.9990 5.9983 23.9959 119.9862 719.9404

as desired.

$\endgroup$

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like