Reputation:
Python newbie here. I am trying to understand the following code to calculate Euler's number:
import math
num(i=10):
sum([1 / math.factorial(z) for z in range(0, i)])
I would really like to get a better grasp on how equations are done in code. I have read many tutorials, but I don't understand them well enough to apply a concept to unique situations like in the above code. Can someone just explain to me what is happening in this code step by step? Additionally, I have not been able to figure out how to do factorials, and it would be very helpful to me if someone would explain how input a factorial in a function (the hard way) without imports.
Upvotes: 1
Views: 57
Reputation: 79208
for you to understand the above code, you first must understand the language itself. e=1/0!+1/1!+1/2!+1/3!+1/4!+...
, so you need to do:
total=0
for i in range(100):
total +=1/math.factorial(i)
print(total)
2.7182818284590455
in case you understand what a for loop is and how it runs. This is much faster compared to what you wrote above.
Now in python there is something called list comprehension. That is, creating a list from a for-loop without necessarily pre-defining the list. so you can do `[i for i in range(10)] which will create a list of 10 elements. You can therefore manipulate each element as you create the list ie
[i**2 for i in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
so in your case you are doing [1/math.factorial(i) for i in range(100)]
. This creates the list [1.0, 1.0, 0.5, 0.16666666666666666, 0.041666666666666664,...]
which you then add the list by calling sum
on this list. ie sum([1/math.factorial(i) for i in range(100)])
factorial is a function that multiplies all numbers from 1 to the specified value. with factorial(0)
set at 1
factorial(3)= 1*2*3
.
thus you can define it as:
def factorial(x):
if x == 0: return 1
val = 1
for i in range(1,x+1):
val *=i
return val
factorial(3)
Out[40]: 6
factorial(4)
Out[41]: 24
You can also use recursiveness to define factorial:
def factorial(x):
if x==0: return 1
else: return x * factorial(x-1)
Upvotes: 1