简体   繁体   English

如何在 python 中乘以负幂的数字

[英]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当我尝试将其乘以负 integer 时,它只会返回一个错误

力量

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)在数学中,这写为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 ).在 numpy 中,您不能通过负 integer 幂来提高整数(阅读内容)。

In python, the ** operator returns the value without any error.在 python 中, **运算符返回值而没有任何错误。

In [6]: A = 20                                                                                                                                                                          

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

You can also use pow() ,您也可以使用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 .如果您使用矩阵,最好确保它们是numpy.matrix类型而不是更通用的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() .要将现有的通用数组转换为矩阵,您还可以将其传递给np.asmatrix()

Once you have a matrix instance M , one way to get the inverse is MI一旦你有一个matrix实例M ,获得逆矩阵的一种方法是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() )为避免“不允许整数”问题,请确保矩阵的dtype是浮点数,而不是 integer(在对matrix()asmatrix()的调用中指定 dtype dtype=float

To Insert power as negative value assume an another variable and name it "pow" and assign that negative value.要将幂作为负值插入,假设另一个变量并将其命名为“pow”并分配该负值。 Now put below in your code.现在把下面的代码。

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

Execute the code and you will see result.执行代码,你会看到结果。 Hope it helps...希望能帮助到你...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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