简体   繁体   中英

Octave compute taylor series of exponential function

I have a problem in Octave to solve but I can't get to beat it.

I have to compute the taylor series of the exponential function with x=1 and the factorial has to be an extra function (self defined).

My solution I have found recently:

This is factorial function to compute factorial.

function answer = factorial(n)
  if(n<0)
    error("no definition for negative factorial");
  endif

  answer=1;

  if(n==0)
    return;
  else
    for i=2:n
        answer = answer*i;
    endfor
  endif
endfunction

This is Taylor function with factorial function included

function answer = taylor(n)
 answer = 1 ./ factorial(n)
endfunction

Now to my Problem:

When I call the sum of the taylor between 0 and 5 (for example)

sum taylor([0:5])

then I get the solution of 1

answer =  1
ans =  1

It solves for every step a number of 1 and at the end it shows 1 which isn't correct. The correct answer would be 2.7182 for e. There is sth wrong in my code. Are you know how to beat that taylor series that I can get the correct answer? Thanks in advance.

Ok I have beaten the Taylor series exponential function problem. :-) Here my solution. The output is a bit strange at the moment but correct.

function answer = taylor(n)
answer = 0
  for i = 0:n
    erg = 1^i / factorial(i)
    answer = answer + erg
  end
endfunction

jo

function answer = factorial(n)
  if(n<0)
    error("no definition for negative factorial");
  endif

  answer=1;

  if(n==0)
    return;
  else
    for i=2:n
        answer = answer*i;
    endfor
  endif
endfunction

At the end only call "taylor(5)" for example and it should compute "e"

There's already a factorial function defined in Octave. It returns a vector if you input a vector, so:

octave:1> factorial(0:6)
ans =
     1     1     2     6    24   120   720

If you really must define your own factorial function, then you should write it vectorized. If so, you can obtain the desired result with simply:

sum(1./factorial(0:20))
ans =  2.71828182845905

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM