简体   繁体   中英

How to mutliply a number with negative power in python

When I try to multiply this by a negative integer it just returns an error

力量

I use:

A = np.array([[1,2,0], [2,4,-2], [0,-2,3]])

From the screenshot, I can see this is homework.

So it asks for the matrix inverse. In maths this is written as A^(-1)

import numpy as np

A = np.array([[1,2,0], [2,4,-2], [0,-2,3]])
np.linalg.inv(A)
array([[-2.  ,  1.5 ,  1.  ],
       [ 1.5 , -0.75, -0.5 ],
       [ 1.  , -0.5 ,  0.  ]])

In numpy, you can not raise integers by negative integer powers (Read this ).

In python, the ** operator returns the value without any error.

In [6]: A = 20                                                                                                                                                                          

In [7]: print(A ** -1)                                                                                                                                                                  
0.05

You can also use pow() ,

In [1]: A = 20

In [2]: pow(20, -1)
Out[2]: 0.05

If you're working with matrices, it's a good idea to ensure that they are instances of the numpy.matrix type rather than the more-generic numpy.ndarray .

import numpy as np
M = np.matrix([[ ... ]])

To convert an existing generic array to a matrix you can also pass it into np.asmatrix() .

Once you have a matrix instance M , one way to get the inverse is MI

To avoid the "integers not allowed" problem, ensure that the dtype of your matrix is floating-point, not integer (specify dtype=float in the call to matrix() or asmatrix() )

To Insert power as negative value assume an another variable and name it "pow" and assign that negative value. Now put below in your code.

pow = -3
value = 5**pow
print(value)

Execute the code and you will see result. Hope it helps...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM