{ "cells": [ { "cell_type": "code", "execution_count": 3, "id": "1e392f52", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "\n", "def power_iteration(A, num_simulations: int):\n", " # Ideally choose a random vector\n", " # To decrease the chance that our vector\n", " # Is orthogonal to the eigenvector\n", " b_k = np.random.rand(A.shape[1])\n", "\n", " for _ in range(num_simulations):\n", " # calculate the matrix-by-vector product Ab\n", " b_k1 = np.dot(A, b_k)\n", " \n", " rayleigh = (b_k.T @ b_k1)/(b_k.T @ b_k)\n", " \n", " # calculate the norm\n", " b_k1_norm = np.linalg.norm(b_k1)\n", "\n", " # re normalize the vector\n", " b_k = b_k1 / b_k1_norm\n", " \n", " \n", "\n", " return b_k, rayleigh\n" ] }, { "cell_type": "code", "execution_count": 4, "id": "4315f9cd", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(array([ 0.09834601, 0.99128595, -0.08763689]), 8.187637295029564)" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "power_iteration(np.asarray([[-1, 1 ,1], [1, 8, -1], [1, -1, -2]]), 10)" ] }, { "cell_type": "code", "execution_count": null, "id": "c99ef5a1", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3.8 (ipykernel)", "language": "python", "name": "python3.8" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.12" } }, "nbformat": 4, "nbformat_minor": 5 }