import numpy as np
from numpy.linalg import matrix_power
a = np.array([[0,1,0],[0,0,1],[0,0,0]])
ae10 = matrix_power(a,10)
print(ae10)
[[0 0 0]
[0 0 0]
[0 0 0]]
注意:如果幂次很大,为了减少在求幂过程中的误差,矩阵中的数字建议用浮点数
Python3numpy.linalg.matrix_powerimport numpy as npfrom numpy.linalg import matrix_powera = np.array([[0,1,0],[0,0,1],[0,0,0]])ae10 = matrix_power(a,10)print(ae10)[[0 0 0] [0 0 0] [0 0 0]]
ylabel('f(t)');
title('Mini Assignment #1');
legend('t^2','sin(2\pit)','Location','northwest')
这个例子中需要注意的点在于:
求幂时需要记住用点(. ^ ),否则会报
#include<stdio.h>
//如果把Pow写在main函数下面的话,需要加一句函数调用
void Pow(int result[20][20],int a[20][20],int n){//注意函数的写法
int i,j,k;
int c[20][20];//用于保存中间结果
for(i=0;i<n;i++)
____tz_zs
np.power
power(x1, x2, /, out=None, *, where=True, casting=‘same_kind’, order=‘K’, dtype=None, subok=True[, signature, extobj])
幂运算(指数运算),对x1中的元素进行x2中元素次幂的计算。
x1 : array_like,底数
x2 : array_l...
在python里,提到矩阵的运算,一定会提起numpy这个扩展库,这里就不多说。
但有些时候,比如算法题里,不允许使用扩展库,就只能自己来实现矩阵的运算了。比如这一题:
给定一个N阶矩阵A,输出A的M次幂(M是非负整数)
A的2次幂
15 22
第一行是一个正整数N、M(1<=N<=30, ...
matlab做矩阵运算时,却出现错误使用 - ,*等, 矩阵维度必须一致的错误
在做矩阵运算加减乘等运算时,会出现矩阵维度错误,原因其实不止是矩阵维度不一致。
1.矩阵维度不一致
A = [1,2,0; 0,1,2;3,3,1];% 为一3x3矩阵
B = [ 1,-2,3;2,1,0;2,-1,3];% 也为一3x3矩阵
C=A+B;
2 0 3
2 2 2
5 2 4
若A不为3*3矩阵,则会出现矩阵维度不一致的错误,若是矩阵相乘即A乘B
for (int j = ; j < 2; j++) {
for (int k = ; k < 2; k++) {
res.a[i][j] += a[i][k] * b.a[k][j] % mod;
res.a[i][j] %= mod;
return res;
Matrix qpow(Matrix a, ll b) {
Matrix res;
res.a[][] = res.a[1][1] = 1;
while (b) {
if (b & 1) res = res * a;
a = a * a;
b >>= 1;
return res;
int main() {
ll n;
while (cin >> n) {
if (n == -1) break;
if (n == ) {
cout << << endl;
continue;
Matrix base;
base.a[][] = base.a[][1] = base.a[1][] = 1;
Matrix res = qpow(base, n - 1);
cout << res.a[][] << endl;
return ;