Raises a matrix to the power of 'power' using binary exponentiation. Args: m: Matrix as a numpy array. power: The power to which the matrix is to be raised. Returns: The matrix raised to the power. Raises: ValueError: If power is negative. >>>
(m: ndarray, power: int)
| 236 | |
| 237 | |
| 238 | def matrix_pow_np(m: ndarray, power: int) -> ndarray: |
| 239 | """ |
| 240 | Raises a matrix to the power of 'power' using binary exponentiation. |
| 241 | |
| 242 | Args: |
| 243 | m: Matrix as a numpy array. |
| 244 | power: The power to which the matrix is to be raised. |
| 245 | |
| 246 | Returns: |
| 247 | The matrix raised to the power. |
| 248 | |
| 249 | Raises: |
| 250 | ValueError: If power is negative. |
| 251 | |
| 252 | >>> m = np.array([[1, 1], [1, 0]], dtype=int) |
| 253 | >>> matrix_pow_np(m, 0) # Identity matrix when raised to the power of 0 |
| 254 | array([[1, 0], |
| 255 | [0, 1]]) |
| 256 | |
| 257 | >>> matrix_pow_np(m, 1) # Same matrix when raised to the power of 1 |
| 258 | array([[1, 1], |
| 259 | [1, 0]]) |
| 260 | |
| 261 | >>> matrix_pow_np(m, 5) |
| 262 | array([[8, 5], |
| 263 | [5, 3]]) |
| 264 | |
| 265 | >>> matrix_pow_np(m, -1) |
| 266 | Traceback (most recent call last): |
| 267 | ... |
| 268 | ValueError: power is negative |
| 269 | """ |
| 270 | result = np.array([[1, 0], [0, 1]], dtype=int) # Identity Matrix |
| 271 | base = m |
| 272 | if power < 0: # Negative power is not allowed |
| 273 | raise ValueError("power is negative") |
| 274 | while power: |
| 275 | if power % 2 == 1: |
| 276 | result = np.dot(result, base) |
| 277 | base = np.dot(base, base) |
| 278 | power //= 2 |
| 279 | return result |
| 280 | |
| 281 | |
| 282 | def fib_matrix_np(n: int) -> int: |