444,100 Members | 2,846 Online
Need help? Post your question and get tips & solutions from a community of 444,100 IT Pros & Developers. It's quick & easy.

# How to get an approx sum of an infinite series in python.

 P: 32 I'm having trouble writing a program that will get me an approximate sum of an infinite series. This is my code: Expand|Select|Wrap|Line Numbers def factorial(n):      if n == 0:          return 1      else:          return n * factorial(n-1)   if    print raw_input()   This is the equation i have to use: How would I get this to finish solving for 'e' ? Sep 26 '10 #1

Variable n is local to the scope of function factorial() and is not defined in the scope of calu(). In addition to that, look at the following:
Expand|Select|Wrap|Line Numbers
1. >>> sum([i for i in range(5)])
2. 10
3. >>> n = 100
4. >>> sum([n for i in range(5)])
5. 500
6. >>> range(5)
7. [0, 1, 2, 3, 4]
8. >>>
As I stated in my previous post: I recommend you study this documentation on Python scope rules.

8 Replies

 Expert Mod 2.5K+ P: 2,851 You got the factorial part. I am using a list comprehension in the code below to determine the value of e. Expand|Select|Wrap|Line Numbers >>> def factorial(n): ...     if n == 0: ...         return 1 ...     return n*factorial(n-1) ...  >>> def calc(u): ...     return sum([1.0/factorial(i) for i in range(0, u+1)]) ...  >>> calc(100) 2.7182818284590455 >>>  Sep 26 '10 #2

 P: 32 how would i have it print the solution afterwards? Sep 26 '10 #3

 Expert Mod 2.5K+ P: 2,851 If you are using Python 2.X: Expand|Select|Wrap|Line Numbers print calc(number) Perhaps you should spend some time perusing a Python beginner's guide. Sep 27 '10 #4

 P: 32 I didn't mean like that, i know how to get something to print. I was asking about the solution to the problem. I still can't get this to work correctly. Here is my code: Expand|Select|Wrap|Line Numbers terms = raw_input('How many terms? ')   def factorial(n):      if n == 0:          return 1      else:          return n * factorial(n-1)   def calu(u):      return sum([1.0/factorial(n) for i in range(0, u + 1)])     print (calu) raw_input() Sep 27 '10 #5

 Expert Mod 2.5K+ P: 2,851 Try this: Expand|Select|Wrap|Line Numbers value = calu(int(terms)) print (value) You also have a problem in calu(). Variable n should be variable i. I recommend you study this documentation on Python scope rules. Sep 27 '10 #6

 P: 32 Why does the variable have to be i instead of n? Sep 27 '10 #7

 Expert Mod 2.5K+ P: 2,851 Variable n is local to the scope of function factorial() and is not defined in the scope of calu(). In addition to that, look at the following: Expand|Select|Wrap|Line Numbers >>> sum([i for i in range(5)]) 10 >>> n = 100 >>> sum([n for i in range(5)]) 500 >>> range(5) [0, 1, 2, 3, 4] >>>  As I stated in my previous post: I recommend you study this documentation on Python scope rules. Sep 27 '10 #8

 P: 32 Alright. Thank you so much for the help bvdet! Sep 27 '10 #9