Reputation:
I have made a python program to calculate e and it worked up until a while ago but now all of the sudden it doesn't work anymore and is behaving very oddly. Here is the source code:
from decimal import *
import time
dig = int(input('Enter number of digits: '))
getcontext().prec = dig +5
def factorial(n):
num = Decimal(1)
while Decimal(n) >= Decimal(1):
num = Decimal(num)*Decimal(n)
n = Decimal(n)-Decimal(1)
return Decimal(num)
def calce(n):
def calce(n):
e = 0
for i in range(0, n+1):
e = e + Decimal((Decimal(2)*Decimal(i)+Decimal(2)))/Decimal(factorial(Decimal(2)*Decimal(i)+1))
return Decimal(e)
n = int(input('How many iterations for e?: '))
t0= time.clock()
numb = str(calce(n))
numb = numb[:-4]
f = open("edigits.txt", 'w')
f.write(str(dig))
f.write(" digits.")
f.write("\n")
f.write(str(n))
f.write("!\n\n")
f.write(numb)
t= str(time.clock() - t0)
f.seek(0, 0)
f.write(t)
f.write(" seconds.\n\n")
f.close()
It even works when I don't write it to a file but when I do this it only gives the time elapsed and doesn't give anything else and sometimes it might give this random number too but that is it... Any help?
Upvotes: 0
Views: 108
Reputation: 10141
def calce(n):
def calce(n):
e = 0
for i in range(0, n+1):
e = e + Decimal((Decimal(2)*Decimal(i)+Decimal(2)))/Decimal(factorial(Decimal(2)*Decimal(i)+1))
return Decimal(e)
the definition of calce(n)
returns None
because you have defined an inner function with the same name. the outer calce(n)
returns None
by default and the statement numb = numb[:-4]
strips off all the values ('None') of num
remove the inner function and define calce(n) as
def calce(n):
e = 0
for i in range(0, n+1):
e = e + Decimal((Decimal(2)*Decimal(i)+Decimal(2)))/Decimal(factorial(Decimal(2)*Decimal(i)+1))
return Decimal(e)
it will work.
Upvotes: 2
Reputation: 365975
The problem is here:
def calce(n):
def calce(n):
e = 0
for i in range(0, n+1):
e = e + Decimal((Decimal(2)*Decimal(i)+Decimal(2)))/Decimal(factorial(Decimal(2)*Decimal(i)+1))
return Decimal(e)
Your calce
function defines a local function, also named calce
, does nothing with it, does nothing else, and just falls off the end, returning None
. So, when you run your program, numb
ends up always being the string 'None'
and nothing else happens.
If you fix this, whether by removing the extra def
line, or by calling the local function (like return calce(n)
after the local definition), you get reasonable results (e.g., 2.71828
when given 5
and 10
as inputs), so I'm pretty sure this is your problem.
However, the f.seek(0, 0)
does mean that you overwrite the start of your output with the timing information, which you almost certainly didn't want.
Upvotes: 2