简体   繁体   English

python中指数函数的近似求和

[英]approximate summation of exponential function in python

I wish to find the approximate sum of exponential function , my code looks like this: 我希望找到指数函数的近似和,我的代码如下所示:

import numpy as np
import matplotlib.pyplot as plt
import math

N = input ("Please enter an integer at which term you want to turncate your summation")
x = input ("please enter a number for which you want to run the exponential summation e^{x}")

exp_sum =0.0

for n in range (0, N):
    factorial = math.factorial(n)
    power     = x**n
    nth_term  = power/factorial
    exp_sum   = exp_sum + nth_term

print exp_sum

Now I tested it for a pair of (x, N) = (1,20) and it returns 2.0, I was wondering if my code is right in this context, if it is, then to get e = 2.71..., how many terms should I consider as N? 现在,我对它进行了一对(x,N)=(1,20)的测试,它返回2.0,我想知道我的代码在这种情况下是否正确,如果正确,则得到e = 2.71 ...,我应考虑多少个术语为N? if my code is wrong please help me fix this. 如果我的代码错误,请帮助我解决此问题。

Which version of python are you using? 您正在使用哪个版本的python? The division that finds nth_term gives different results in python 2.x and in version 3.x. 查找nth_term的除法在python 2.x和版本3.x中给出不同的结果。

It seems like you are using version 2.x. 似乎您正在使用2.x版。 The division you use gives only integer results, so after the first two lines loops (1/factorial(0) + 1/factorial(1)) you are only adding zeros. 您使用的除法仅给出整数结果,因此在前两行循环(1 / factor(0)+ 1 / factor(1))之后,您仅添加了零。

So either use version 3.x, or replace that line with 因此,请使用3.x版本,或将该行替换为

nth_term  = float(power)/factorial

Or, as a comment suggests, make python 2.x do division like 3.x by adding the line 或者,如注释所示,通过添加以下代码行使python 2.x像3.x一样进行除法

from __future__ import division

at or very near the beginning of the module. 在模块开始处或附近。

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

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