简体   繁体   English

如何使用 Python 中的 map 和 reduce 函数为 e^x 编写泰勒级数?

[英]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.我需要一些帮助来用 Python 编写 e^x 的泰勒级数。 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.我也试图更多地了解 Python。

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对于那些不知道泰勒级数是什么的人: https : //en.wikipedia.org/wiki/Taylor_series

But basically I'm taking the sum as shown here: Taylor Series for e^x但基本上我取的总和如下所示: 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.708333333333333 (e 表示 4+1 项)

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

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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