1

I have tried the top two solutions here and the bottom solution since it dealt with numpy but nothing worked.

I wanted to take 80.0 divided each element of my array name that a new array dx.

import numpy

L = 80.0
N = []


for n in range(-4, 10):
    N.append(str(2 ** N))


N = np.array([N])

This is the set up. So what I have tried is:

  1. dx = L / N
  2. dx = map(lambda x: L / x, N)
    dx = np.array([dx])
    
  3. Lastly, keeping N as a list and keeping N as a numpy array and doing

    dx = [x / N for x in N]
    dx = np.array([dx])
    

Unfortunately, I haven't been able to find a post that helped or anything in the documentation. What can I do to achieve the desired result?

4

2 回答 2

4

您的代码包含几个错误,并且您有很多不必要的强制转换,但是:您为什么不直接使用 numpy 尝试呢?

像这样的东西:

import numpy as np

L = 80.0
N = 2 ** np.arange(-4, 10, dtype=np.float64)
dx = L / N

给你预期的结果

array([  1.28000000e+03,   6.40000000e+02,   3.20000000e+02,
         1.60000000e+02,   8.00000000e+01,   4.00000000e+01,
         2.00000000e+01,   1.00000000e+01,   5.00000000e+00,
         2.50000000e+00,   1.25000000e+00,   6.25000000e-01,
         3.12500000e-01,   1.56250000e-01])

顺便提一句。您还dtype可以float在使用点时隐式强制为:

N = 2 ** np.arange(-4., 10.)
于 2013-09-25T12:26:44.090 回答
2

您可以使用列表推导在一行中完成。

In [8]: N=[80.0/(2**n) for n in range(-4,10)]

In [10]: print N
[1280.0, 640.0, 320.0, 160.0, 80.0, 40.0, 20.0, 10.0, 5.0, 2.5, 1.25, 0.625, 0.3125, 0.15625]

您可以避免将 Numpy 用于此类任务。

与此等效的 for 循环将是(不预先分配 N):

In [11]: N=[]

In [12]: for n in range(-4,10):
   ....:     N.append(80.0/(2**n))
   ....:     

In [13]: print N
[1280.0, 640.0, 320.0, 160.0, 80.0, 40.0, 20.0, 10.0, 5.0, 2.5, 1.25, 0.625, 0.3125, 0.15625]
于 2013-09-25T12:45:57.933 回答