Reputation: 25
I have a formula that uses the previous element to find the current element:
p(i) = 1 / (- 2 + p(i-1))
The code I have to find this is:
p = []
po = 0
i = .01
while i < 1:
po = (-1) / (-2 + po)
p.append(po)
i = i + .01
print p
What I'm getting is :
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
My first value (if po
is originally zero) should be 1/2
.
Any ideas why I'm only getting zeros?
Upvotes: 0
Views: 94
Reputation: 16515
As user @blhsing pointed out in his answer, the problem seems to be interger division: when dividing integers, the result is rounded down to yield a new integer.
By converting one of the arguments of the division into a float
, the division will also return a float
. It does not matter which of the 3 numbers you change into a float
, changing one of them is sufficient to produce the correct result:
po = 0
to po = 0.0
po = (-1.0) / (-2 + po)
po = (-1) / (-2.0 + po)
Furthermore, I find your use of the i
variable a bit strange. May I suggest a forloop using xrange()
?
p = []
po = 0
# the '_' is used to say "I dont care about this value", so this
# runs the loop the specified amout of times
for _ in xrange(10):
po = (-1.0) / (-2 + po)
p.append(po)
print p
Upvotes: 1
Reputation: 107085
In Python 2, a division involving only integers would always result in an integer, rounded down. You should use a floating number for division instead:
po = -1.0 / (-2 + po)
Upvotes: 3