存储数组中的积分值,然后使用该新数组

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

我是 Python 的新手,所以我真的很难解决这个问题。我想定义一个函数,对不同值的数组进行一定的计算,将这些新计算的值存储在一个新数组中,然后在另一个计算中使用这些新值。我的尝试是这样的:

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

好吧,这个脚本有点乱,让我们解压一下。我从未使用过 scipy.integrate.quad,但我查了一下,并通过测试确定这些是 quad 的有效参数。有更有效的方法可以做到这一点,但为了保存,我会尽量保持脚本的整体结构,只修复错误和错误。所以,据我了解,你想这样写:

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)

如果此解决方案正确,请将其标记为已接受。

希望对您有所帮助!