在 Python 中使用麦克劳林级数逼近 e^x [英] Approximation of e^x using Maclaurin Series in Python

查看:101
本文介绍了在 Python 中使用麦克劳林级数逼近 e^x的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一个名为 my_exp(x) 的函数中使用麦克劳林级数来近似 e^x,我相信到目前为止我所做的一切都是正确的,但我得到了不正确的近似值无论我尝试什么号码.

导入数学对于范围 (x) 中的 i:exp = 1 + ((x**i)/math.factorial(i))打印(exp)

例如,每当我尝试 my_exp(12) 我得到 18614.926233766233 而不是 162754.79141900392帮助?

解决方案

你的问题是 e^x 级数是一个无限级数,所以只对级数的前 x 项求和是没有意义的.

>

def myexp(x):e=0for i in range(0,100): #Sum the first 100项e=e+(x**i)/math.factorial(i)返回 e

您还可以定义结果的精度并获得更好的解决方案.

def myexp(x):e=0压力=0.0001s=1我=1当 s>pre:e=e+ss=(x**i)/math.factorial(i)我=我+1返回 e

I'm trying to approximate e^x using the Maclaurin series in a function called my_exp(x), I believe everything I've done so far is right but I'm getting incorrect approximations for whatever number I try.

import math
for i in range (x):
    exp = 1 + ((x**i)/math.factorial(i))
print(exp)

For example, whenever I try my_exp(12) I get 18614.926233766233 instead of 162754.79141900392 Help?

解决方案

Your problem is that the e^x series is an infinite series, and so it makes no sense to only sum the first x terms of the series.

def myexp(x):
  e=0
  for i in range(0,100): #Sum the first 100 terms of the series
    e=e+(x**i)/math.factorial(i)
  return e

You can also define the precision of your result and get a better solution.

def myexp(x):
    e=0
    pres=0.0001
    s=1
    i=1
    while s>pres:
        e=e+s
        s=(x**i)/math.factorial(i)
        i=i+1
    return e

这篇关于在 Python 中使用麦克劳林级数逼近 e^x的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆