Calculates the first n (0-indexed) Fibonacci numbers using a simplified form of Binet's formula: https://en.m.wikipedia.org/wiki/Fibonacci_number#Computation_by_rounding NOTE 1: this function diverges from fib_iterative at around n = 71, likely due to compounding floating-point
(n: int)
| 199 | |
| 200 | |
| 201 | def fib_binet(n: int) -> list[int]: |
| 202 | """ |
| 203 | Calculates the first n (0-indexed) Fibonacci numbers using a simplified form |
| 204 | of Binet's formula: |
| 205 | https://en.m.wikipedia.org/wiki/Fibonacci_number#Computation_by_rounding |
| 206 | |
| 207 | NOTE 1: this function diverges from fib_iterative at around n = 71, likely |
| 208 | due to compounding floating-point arithmetic errors |
| 209 | |
| 210 | NOTE 2: this function doesn't accept n >= 1475 because it overflows |
| 211 | thereafter due to the size limitations of Python floats |
| 212 | >>> fib_binet(0) |
| 213 | [0] |
| 214 | >>> fib_binet(1) |
| 215 | [0, 1] |
| 216 | >>> fib_binet(5) |
| 217 | [0, 1, 1, 2, 3, 5] |
| 218 | >>> fib_binet(10) |
| 219 | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] |
| 220 | >>> fib_binet(-1) |
| 221 | Traceback (most recent call last): |
| 222 | ... |
| 223 | ValueError: n is negative |
| 224 | >>> fib_binet(1475) |
| 225 | Traceback (most recent call last): |
| 226 | ... |
| 227 | ValueError: n is too large |
| 228 | """ |
| 229 | if n < 0: |
| 230 | raise ValueError("n is negative") |
| 231 | if n >= 1475: |
| 232 | raise ValueError("n is too large") |
| 233 | sqrt_5 = sqrt(5) |
| 234 | phi = (1 + sqrt_5) / 2 |
| 235 | return [round(phi**i / sqrt_5) for i in range(n + 1)] |
| 236 | |
| 237 | |
| 238 | def matrix_pow_np(m: ndarray, power: int) -> ndarray: |
nothing calls this directly
no outgoing calls
no test coverage detected