简体   繁体   中英

How can I write the Taylor Series for e^x using map and reduce functions in Python?

I need some help with writing the Taylor Series of e^x in Python. However, I am quite limited to the kind of functions I can use:

  • map
  • reduce
  • range
  • factorial
  • 'helper' functions written by yourself

Any pointers or help would be much appreciated. I am trying to get to know more about Python in general as well.

This is what I have so far in terms of code:

def taylorApproxE(lastIter):
    '''approximates the value of e using Taylor Series.'''
    L = range(lastIter + 1)

    def sum(x,y):
        return x + y

    def iter(x,y):
        return (x**y)/factorial(y)

    return reduce(sum, map(iter, L))

Every time I attempt to use this function in my terminal, I get

TypeError: iter() missing 1 required positional argument: 'y'

For those who don't know what a Taylor Series is: https://en.wikipedia.org/wiki/Taylor_series

But basically I'm taking the sum as shown here: Taylor Series for e^x

What should happen when I use the function is

taylorApproxE(4) = 2.708333333333333

Edit: I apologize for not being clear enough in the first draft of this question. I am extremely new to this website and have not been well-accustomed to the rules of posting. I hope I did not offend with my transgressions in formatting or phrasing.

you can use below code with one or two parameters:

for example:

taylorApproxE(4) = 2.708333333333333 (e for 4+1 terms)

taylorApproxE(4,2) = 7 (e^2 for 4+1 terms)

from math import factorial
from functools import reduce

def taylorApproxE(lastIter, x_in=1):
    n_range = range(lastIter + 1)
    return reduce(lambda y, z: y + z, map(lambda x: x_in ** x / factorial(x), n_range))


print(taylorApproxE(4))

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