Reputation: 6206
so i'd like to iterate through the Fibonacci sequence (but this could apply to any non-arithmetic sequence). i've written a function fibonacci:
from math import sqrt
def F(n):
return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))
which returns the fibonacci number for any given input. this bit seems to work OK. However, I'd like to include a couple of conditions, like even numbers and F(n) below a certain limit. I tried using an if loop like this:
def ser():
count = 0
for i in F(n):
if F(n) <= 4000000 and F(n) % 2 == 0:
count = count + F(n)
But it seems like you can't use F(n) in the iteration for loop like I did. I'm a complete novice at python, so how would be best to use the F(n) function I created to iterate over the sequence? Thanks
Upvotes: 2
Views: 861
Reputation: 30258
What is the range of n
that you are looking to run the fibonacci number on?
Your definition of fibonacci is in a closed form, so you need to give each number you want to calculate:
import itertools
count = 0
for n in itertools.count(1):
if F(n) > 4000000:
break
if F(n) % 2 == 0:
count += F(n)
You can use a generator form of fibonacci and use itertools.takewhile()
to limit the output:
def F():
a,b = 0,1
yield b
while True:
a, b = b, a + b
yield b
count = sum(f for f in it.takewhile(lambda x: x <= 4000000, F()) if f % 2 == 0)
Upvotes: 1