Accuracy in Numbers
I've written a quick (and messy) little script that calculates euler's constant where n is input by the user. Code:
def factorial(n):
f=1
while (n>0):
f=f*n
n=n-1
return f
n=float(raw_input("Number: "))
a=[1.0]
s=n
while (s>0):
k=1/(factorial(n))
s=s-1
a.append(k)
n=s
t=0
for line in a:
t += line
print(t)
When n = 5, the program's answer is 2.71666666667 I was expecting 2.718055556
I feel like this has something to do with number types, i'm using int and floats and haven't had any success using long.
6 comments · 100% upvoted · other discussions
Did you try inspecting the contents of
a?Did you try taking the reciprocal of the difference between the expected and actual results?
(You're getting the result you're supposed to. The result you're expecting is what you should get for
n = 6.)That said, there are many basic techniques you can learn to clean up this code. The basic idea is to stop writing loops that control everything a step at a time, and start just describing what you want. Also, if you're going to loop over a specific set of values (say, numbers from 0 up to n), then do so, with a for-loop.
whileis for things that are too complicated to express in that way, or which depend on other external factors.The
+1s are becauserange(x)produces numbers from 0 up to x-1, inclusive. That is actually usually what we want (trust me!), but not here. Notice that in the final line, we include0in the list of values that we use forfactorialcalls; that takes care of the initial[1.0]value you had inain the original code. You could have done this, too; yourfactorialimplementation (as well as mine) gives the correct result forfactorial(0). This is another important principle: "special cases aren't special enough" (and from personal experience, 0 very, very often isn't a special case at all, even though you initially expect it to be).jackzombie [OP] 3 points · Jun 2012
Thank you very much for the explanation!
I fixed the s and n part of my code as soon as I submitted this. I just separated them while building the script to reduce any confusion while reading and rereading my code.
It's going to take a few more read throughs before I completely grasp what you're saying, but I am very thankful you took the time to explain this!
ewiethoff 2 points · Jun 2012 · proceedest on to 3
Couple things. According to Wikipedia, you're talking about Euler's number, not Euler's constant. Second, zahlman's
factorialcode has an error.f *= nshould bef *= 1. Ergo, be sure to test each function individually.Here's a variation on zahlman's technique: