Consider a sphere, composed of shells of varying density.
I have two arrays, one for the outer radius of each shell (rad[]) and one for the density of each shell (den[]). I want to calculate the mass, out to a given radius, called mass[].
The following for-loop approach achieves the desired result by first finding the mass of the innermost shell (the inner-radius is zero, so it's a sphere), then the mass of each subsequent shell - added to the previous (summed) mass:
mass = numpy.zeros(len(rad)) # create array
mass[0] = den[0]**(rad[0]**3) # find inner sphere mass
for i in range(1,len(mass)):
mass[i] = mass[i-1] + den[i]*(rad[i]**3 - rad[i-1]**3) # Find mass out to shell i
Note: I only need the scalings, so I'm not worried about factors of pi.
Can anyone explain why the following slicing result does not achieve the same result?
mass = numpy.zeros(len(rad))
mass[0] = den[0]*(rad[0]**3)
mass[1:] = mass[0:-1] + den[1:]*(rad[1:]**3-rad[0:-1]**3)
massand then uses that element to compute the next. in the second case the old value of the element is used to compute the new one, because the value of mass will be set only after the expression after the equals sign is evaluated. simple as that.test = linspace(1,10,num=10); test[1:] += test[0:-1]works differently. (I am almost done with my revision to that effect).mass = (den * np.diff(np.r_[0, rad]**3)).cumsum()