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
  • 1
    why do you cast your int into str ? Commented Sep 25, 2013 at 12:25
  • @georgesl I thought it had to be a string to go into a list. Commented Sep 25, 2013 at 12:25
  • 3
    Nope, list can support any type, also different ones in the same list. Commented Sep 25, 2013 at 12:27
  • Further, this would give you a numpy array of strings, which cannot be divided with ints. Commented Sep 25, 2013 at 13:41

2 Answers 2

4

Your code contains several bugs and you have a lot of unnecessary casts, but however: why don't you try this with numpy directly?

Something like this:

import numpy as np

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

gives you the expected result

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

Btw. you can also implicitly force the dtype to be float when using dots:

N = 2 ** np.arange(-4., 10.)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. You have an extra r in arange.
2

You could do it in a single line using List comprehensions.

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]

You can avoid using Numpy for such tasks.

The for loop equivalent of this would be (without preallocating 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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.