首页 > 解决方案 > How to use logspace() in numpy array?

问题描述

I'm trying to generate the value between given range i.e. values from 10^-1 up to 10^−14 and I'm getting a wrong output

I have implemented the logic to understand this logspace, but couldn't figure it out.

import numpy as np

delta = np.logspace(1, 14, dtype=np.float64)
print(delta)

Expected output is :

>>> print(delta)
[  1.00000000e-01   1.00000000e-02   1.00000000e-03   1.00000000e-04
   1.00000000e-05   1.00000000e-06   1.00000000e-07   1.00000000e-08
   1.00000000e-09   1.00000000e-10   1.00000000e-11   1.00000000e-12
   1.00000000e-13   1.00000000e-14]

标签: pythonpython-3.xnumpy

解决方案


From the documentation:

In linear space, the sequence starts at base ** start (base to the power of start) and ends with base ** stop.

So np.logspace(-1, -14, 14) gives:

array([1.e-01, 1.e-02, 1.e-03, 1.e-04, 1.e-05, 1.e-06, 1.e-07, 1.e-08,
   1.e-09, 1.e-10, 1.e-11, 1.e-12, 1.e-13, 1.e-14])

Or with more "precision" (as asked in the comment):

np.set_printoptions(formatter=dict(float='{:10.8e}'.format))
np.logspace(-1, -14, 14)

Gives:

[1.00000000e-01 1.00000000e-02 1.00000000e-03 1.00000000e-04
 1.00000000e-05 1.00000000e-06 1.00000000e-07 1.00000000e-08
 1.00000000e-09 1.00000000e-10 1.00000000e-11 1.00000000e-12
 1.00000000e-13 1.00000000e-14]

Note: this changes every numpy array with floats that you print afterwards..!


推荐阅读