Search code examples
pythonarraysscipynumerical-integration

Store values of integration from array, then use that new array


I'm new to Python so I'm really struggling with this. I want to define a function, have a certain calculation done to it for an array of different values, store those newly calculated values in a new array, and then use those new values in another calculation. My attempt is this:

import numpy as np
from scipy.integrate import quad

radii = np.arange(10) #array of radius values

def rho(r): 
    return (r**2) 

for i in range(len(radii)):
    def M[r]: #new array by integrating over values from 0 to radii
        scipy.integrate.quad(rho(r), 0, radii[i])

def P(r):
    return (5*M[r]) #make new array using values from M[r] calculated above

Solution

  • Alright, this script is a bit of a mess, so let's unpack this. I've never used scipy.integrate.quad but I looked it up, and along with testing it have determined that those are valid arguments for quad. There are more efficient ways to do this, but in the interests of preservation, I'll try to keep the overall structure of your script, just fixing the bugs and errors. So, as I understand it, you want to write this:

    import numpy as np
    from scipy.integrate import quad
    
    # Here's where we start to make changes. First, we're going to define the function, taking in two parameters, r and the array radii.
    # We don't need to specify data types, because Python is a strongly-typed language.
    # It is good practice to define your functions before the start of the program.
    def M(r, radii):
        # The loop goes _inside_ the function, otherwise we're just defining the function M(r) over and over again to a slightly different thing!
        for i in range(len(radii)):
            # Also note: since we imported quad from scipy.integrate, we only need to reference quad, and in fact referencing scipy.integrate.quad just causes an error!
            output[i] = quad(r, 0, radii[i])
            # We can also multiply by 5 in this function, so we really only need one. Hell, we don't actually _need_ a function at all,
            # unless you're planning to reference it multiple times in other parts of a larger program.
            output[i] *= 5
        return output
    
    # You have a choice between doing the maths _inside_ the main function or in maybe in a lambda function like this, which is a bit more pythonic than a 1-line normal function. Use like so:
    rho = lambda r: r**2 
    
    # Beginning of program (this is my example of what calling the function with a list called radii might be)
    radii = np.arange(10)
    
    new_array = M(rho, radii)
    

    If this solution is correct, please mark it as accepted.

    I hope this helps!