• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python numpy.power()数组元素求n次方案例

python 搞代码 4年前 (2022-01-08) 19次浏览 已收录 0个评论
文章目录[隐藏]

这篇文章主要介绍了python numpy.power()数组元素求n次方案例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

如下所示:

 numpy.power(x1, x2)

数组的元素分别求n次方。x2可以是数字,也可以是数组,但是x1和x2的列数要相同。

 >>> x1 = range(6) >>> x1 [0, 1, 2, 3, 4, 5] >>> np.power(x1, 3) array([ 0,  1,  8, 27, 64, 125])
 >>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0] >>> np.power(x1, x2) array([ 0.,  1.,  8., 27., 16.,  5.])
 >>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]]) >>> x2 array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]]) >>> np.power(x1, x2) array([[ 0, 1, 8, 27, 16, 5], [ 0, 1, 8, 27, 16, 5]])

补充:python求n次方的函数_python实现pow函数(求n次幂,求n次方)

类型一:求n次幂

实现 pow(x, n),即计算 x 的 n 次幂函数。其中n为整数。pow函数的实现――leetcode

解法1:暴力法

不是常规意义上的暴力,过程中通过动态调整底数的大小来加快求解。代码如下:

 class Solution: def myPow(self, x: float, n: int) -> float: judge = True if n0: if n>=count: final *= tmp tmp = tmp*x n -= count count +=1 else: tmp /= x count -= 1 return final if judge else 1/final 

解法2:根据奇偶幂分类(递归法,迭代法,位运算法)

如果n为偶数,则pow(x,n) = pow(x^2, 来源gao@daima#com搞(%代@#码网n/2);

如果n为奇数,则pow(x,n) = x*pow(x, n-1)。

递归代码实现如下:

 class Solution: def myPow(self, x: float, n: int) -> float: if n</div><p>迭代代码如下:</p><div class="gaodaimacode"><pre class="prettyprint linenums"> class Solution: def myPow(self, x: float, n: int) -> float: judge = True if n 0: if n%2 == 0: x *=x n //= 2 final *= x n -= 1 return final if judge else 1/final 

python位运算符简介

其实跟上面的方法类似,只是通过位运算符判断奇偶性并且进行除以2的操作(移位操作)。代码如下:

 class Solution: def myPow(self, x: float, n: int) -> float: judge = True if n 0: if n & 1: #代表是奇数 final *= x x *= x n >>= 1 # 右移一位 return final if judge else 1/final 

类型二:求n次方

实现 pow(x, n),即计算 x 的 n 次幂函数。其中x大于0,n为大于1整数。

解法:二分法求开方

思路就是逐步逼近目标值。以x大于1为例:

设定结果范围为[low, high],其中low=0, high = x,且假定结果为r=(low+high)/2;

如果r的n次方大于x,则说明r取大了,重新定义low不变,high= r,r=(low+high)/2;

如果r的n次方小于x,则说明r取小了,重新定义low=r,high不变,r=(low+high)/2;

代码如下:

 class Solution: def myPow(self, x: float, n: int) -> float: # x为大于0的数,因为负数无法开平方(不考虑复数情况) if x>1: low,high = 0,x else: low,high =x,1 while True: r = (low+high)/2 judge = 1 for i in range(n): judge *= r if x >1 and judge>x:break # 对于大于1的数,如果当前值已经大于它本身,则无需再算下去 if x <1 and judge if abs(judge-x)x: high = r else: low = r 

以上就是python numpy.power()数组元素求n次方案例的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python numpy.power()数组元素求n次方案例

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址