python数列的平方_如何使2D numpy数组平方或提升为幂(元素级)?

>>> import numpy

>>> print numpy.power.__doc__

power(x1, x2[, out])

First array elements raised to powers from second array, element-wise.

Raise each base in `x1` to the positionally-corresponding power in

`x2`. `x1` and `x2` must be broadcastable to the same shape.

Parameters

----------

x1 : array_like

The bases.

x2 : array_like

The exponents.

Returns

-------

y : ndarray

The bases in `x1` raised to the exponents in `x2`.

Examples

--------

Cube each element in a list.

>>> x1 = range(6)

>>> x1

[0, 1, 2, 3, 4, 5]

>>> np.power(x1, 3)

array([ 0, 1, 8, 27, 64, 125])

Raise the bases to different exponents.

>>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]

>>> np.power(x1, x2)

array([ 0., 1., 8., 27., 16., 5.])

The effect of broadcasting.

>>> 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]])

>>>

精密度

根据评论中@GarethRees反对意见所讨论的数值精度观察:>>> a = numpy.ones( (3,3), dtype = numpy.float96 ) # yields exact output

>>> a[0,0] = 0.46002700024131926

>>> a

array([[ 0.460027, 1.0, 1.0],

[ 1.0, 1.0, 1.0],

[ 1.0, 1.0, 1.0]], dtype=float96)

>>> b = numpy.power( a, 2 )

>>> b

array([[ 0.21162484, 1.0, 1.0],

[ 1.0, 1.0, 1.0],

[ 1.0, 1.0, 1.0]], dtype=float96)

>>> a.dtype

dtype('float96')

>>> a[0,0]

0.46002700024131926

>>> b[0,0]

0.21162484095102677

>>> print b[0,0]

0.211624840951

>>> print a[0,0]

0.460027000241

性能>>> c = numpy.random.random( ( 1000, 1000 ) ).astype( numpy.float96 )

>>> import zmq

>>> aClk = zmq.Stopwatch()

>>> aClk.start(), c**2, aClk.stop()

(None, array([[ ...]], dtype=float96), 5663L) # 5 663 [usec]

>>> aClk.start(), c*c, aClk.stop()

(None, array([[ ...]], dtype=float96), 6395L) # 6 395 [usec]

>>> aClk.start(), c[:,:]*c[:,:], aClk.stop()

(None, array([[ ...]], dtype=float96), 6930L) # 6 930 [usec]

>>> aClk.start(), c[:,:]**2, aClk.stop()

(None, array([[ ...]], dtype=float96), 6285L) # 6 285 [usec]

>>> aClk.start(), numpy.power( c, 2 ), aClk.stop()

(None, array([[ ... ]], dtype=float96), 384515L) # 384 515 [usec]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值