LoginSignup
3
1

More than 5 years have passed since last update.

【numpy】np.arange()を使用した負の指数計算トラップ

Last updated at Posted at 2017-09-23

np.arange()を使用して
n^-3, n^-2, 2^-1...
のように一定範囲の負の指数計算をnumpyで計算しようとしたらちょっと躓いたのでメモ。

まず書いてみる

2**np.arange(-3, -1)

エラー発生。

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-d719d82f8b72> in <module>()
----> 1 2**np.arange(-3, -1)

ValueError: Integers to negative integer powers are not allowed.

負の整数は許されてないだと?

ちなみにrange()使うとこう書ける

[2**i for i in range(-3, 0)]
->  [0.125, 0.25, 0.5]

ただ、range()の弱点はstepに小数を刻めないことなんだよね。

np.arange()使って小数刻みで計算させると?

2**np.arange(-3, 0, 0.5)
-> array([ 0.125, 0.1767767, 0.25, 0.35355339, 0.5, 0.70710678])

普通にうまくいった。
ということは、、、負の指数もfloat扱いしてやればうまくいくのかな?

2**np.arange(-3, 0, dtype=float)
-> array([ 0.125,  0.25 ,  0.5  ])

なるほど。明示的にfloatでarangeしてあげると良いのですね!

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1