using python numpy linspace in for loop

23,890

Solution 1

You should not use the output of linspace to index an array! linspace generates floating point numbers and array indexing requires an integer.

From your code it looks like what you really want is something like this:

z_bin = numpy.linspace(0.0, 10.0, 21)

for i in range(len(z_bin)-1):
    zmin = z_bin[i]
    zmax = z_bin[i+1]

    # do some things with zmin/zmax

zmin and zmax will still be floating point (decimal) numbers.

Solution 2

An easier way to do this would be to use the zip function:

z_bin = numpy.linspace(0.0, 10.0, 21)

for z_min, z_max in zip(z_bin[:-1], z_bin[1:]):
    print z_min, z_max
Share:
23,890
CuriousGeorge119
Author by

CuriousGeorge119

Undergrad trying to finish BS and get into a great Grad school program!!!

Updated on July 28, 2020

Comments

  • CuriousGeorge119
    CuriousGeorge119 almost 4 years

    I am trying to use linspace in a for loop. I would like intervals of 0.5 between 0 and 10. It appears the z_bin is executing properly.

    My question: How can I use linspace correctly in the for loop in place of the range function that is shown next to it in the comment line? What do I need to change in the loop as I move from working with integers to working with decimals?

    z_bin = numpy.linspace (0.0,10.0,num=21) 
    print 'z_bin: ', z_bin
    num = len(z_bin)
    
    grb_binned_data = []
    for i in numpy.linspace(len(z_bin)-1): #range(len(z_bin)-1):
        zmin = z_bin[i]
        zmax = z_bin[i+1]
        grb_z_bin_data = []
        for grb_row in grb_data:
            grb_name = grb_row[0]
            ra = grb_row[1]
            dec = grb_row[2]
            z = float(grb_row[3])
            if z > zmin and z <= zmax:
                grb_z_bin_data.append(grb_row)
        grb_binned_data.append(grb_z_bin_data) 
    
  • CuriousGeorge119
    CuriousGeorge119 almost 10 years
    dshepard: Excellent!!! Thank you very much for your response. Informative and clear, I really appreciate it
  • Evan
    Evan almost 10 years
    Be careful with using arange like this. It works for the case listed, but whether or not it includes the endpoint depends on floating point rounding. For instance, numpy.arange(0.0, 20.0, 2.0/3.0) does not return the same answer as numpy.linspace(0.0, 20.0, 31).
  • dshepherd
    dshepherd almost 10 years
    Good point, in fact the documentation says that linspace should be used for non-integral steps, I'll change it in my answer.