"Fossies" - the Fresh Open Source Software Archive

Member "NZMATH-1.2.0/nzmath/sequence.py" (19 Nov 2012, 1096 Bytes) of package /linux/misc/old/NZMATH-1.2.0.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. For more information about "sequence.py" see the Fossies "Dox" file reference documentation.

    1 def generator_fibonacci(n=None):
    2     """
    3     Generate Fibonacci number up to n-th term if n is assigned
    4     else infinity.
    5     """
    6     a = 0
    7     b = 1
    8 
    9     if None == n:
   10         while True:
   11             yield b
   12             a += b
   13             yield a
   14             b += a
   15     else:
   16         count = 0
   17         while True:
   18             yield b
   19             count += 1
   20             if n <= count:
   21                 break
   22             a += b
   23 
   24             yield a
   25             count += 1
   26             if n <= count:
   27                 break
   28             b += a
   29 
   30 
   31 FIBONACCI = {0:0, 1:1}
   32 def fibonacci(n):
   33     """
   34     param non-negative integer n
   35     return the n-th term of the Fibonacci
   36     effect FIBONACCI[n] = fibonacci(n)
   37     """
   38     if n < 0:
   39         raise ValueError("fibonacci(n)  0 <= n  ?")
   40 
   41     if n in FIBONACCI:
   42         return FIBONACCI[n]
   43 
   44     m = n >> 1
   45     if n & 1 == 0:
   46         f1 = fibonacci(m - 1)
   47         f2 = fibonacci(m)
   48         FIBONACCI[n] = (f1 + f1 + f2) * f2
   49     else:
   50         f1 = fibonacci(m)
   51         f2 = fibonacci(m + 1)
   52         FIBONACCI[n] = f1 ** 2 + f2 ** 2
   53 
   54     return FIBONACCI[n]