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? if my code is wrong please help me fix this.
Which version of python are you using? The division that finds nth_term
gives different results in python 2.x and in version 3.x.
It seems like you are using version 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.
So either use version 3.x, or replace that line with
nth_term = float(power)/factorial
Or, as a comment suggests, make python 2.x do division like 3.x by adding the line
from __future__ import division
at or very near the beginning of the module.
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.