# ## MIT License

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#

# In[97]:
import numpy as np
import numpy.linalg as la
np.set_printoptions(linewidth=150, precision=3, suppress=True)
# Consider a random diagonal matrix $A$ with entries sorted by magnitude:
# In[98]:
n = 10
eigvals = np.array(sorted(np.random.randn(n), key=abs, reverse=True))
D = np.diag(eigvals)
D
# In[99]:
D @ D @ D
# In[100]:
tmp = D @ D @ D
tmp / tmp[0,0]
# In[101]:
tmp = D @ D @ D @ D @ D @ D @ D @ D @ D @ D @ D @ D
tmp / tmp[0,0]
# This works just as well if the matrix is not diagonalized:
# In[102]:
X = np.random.randn(n, n)
Xinv = la.inv(X)
A = X @ D @ Xinv
A
# In[103]:
A @ A @ A
# At first, it doesn't look like there is much happening, however:
# In[104]:
Apower = A @ A @ A @ A @ A @ A @ A @ A @ A @ A @ A @ A @ A
# In[105]:
tmp = Xinv @ Apower @ X
tmp / tmp[0,0]
# Let $\boldsymbol{y} = A^{13} \boldsymbol{x}$?
# In[106]:
x = np.random.randn(n)
y = Apower @ x
# Anything special about $\boldsymbol{y}$?
# In[107]:
la.norm(A @ y - D[0,0] * y, 2)/la.norm(y, 2)
# Is there a better way to compute $\boldsymbol y$?
# In[109]:
y2 = x
for i in range(13):
y2 = A @ y2
la.norm(y2-y)
# In[ ]: