python - 从数组存储积分值,然后使用该新数组
问题描述
我是 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)
如果此解决方案正确,请将其标记为已接受。
我希望这有帮助!
推荐阅读
- c - 使用 void 指针在 C 中重新编程 Calloc / Realloc
- linux - Linux/Mac 上 Unity3D 项目向导项目列表存储在哪里?
- python - 删除标签冲突的行
- python - Python:使用matplotlib后的unicode问题
- php - 喜欢系统,我该如何解决?
- python-3.x - 有没有办法遍历列表以添加到硒代码中?
- node.js - AWS Lambda 工作一次,然后失败十几次
- java - 如何在java中将单个数量添加到hashmap键和值
- r - 在汇总表中显示具有零个因子实例的单元格,而不是忽略它们
- r - 需要获取 R 中列的总数