好的,所以我的辛普森规则被定义为:
def simpsonsRule(func, a, b, n, p0, r0):
if n%2 == 1:
return "Not applicable"
else:
h = (b - a) / float(n)
s = func(a, p0, r0) + sum((4 if i%2 == 1 else 2) * func(a+i*h, p0, r0) for i in range(1,n)) + func(b, p0, r0)
return s*h/3.0
然而,当我做类似的事情时:
def integrate_NFW(rx,ps,rs):
rho = ps/((r/rs)*((1+(r/rs))**2))
function_result = rho * 4.0 * np.pi * rx**2
return function_result
def chisqfuncNFW(iter_vars):
global v_model
#Normalizes p0 (p0 is too large relative to rc)
ps = iter_vars[0] * 3.85e+09
rs = iter_vars[1]
for index in range(0, am):
integral_result = simpsonsRule(integrate_NFW, 0.0, r[index], 200, ps, rs)
print(integral_result)
当你打印出integral_result时,它返回一个数字数组:
[ 1.58771810e+13 3.68633515e+12 1.60346051e+12 8.81279407e+11
5.37962555e+11 3.54826396e+11 2.49107306e+11 1.80747811e+11
1.36318422e+11 1.05440828e+11 8.32851651e+10 6.66410643e+10
5.41730944e+10 4.48302130e+10]
所以integral_result = simpsonsRule(integrate_NFW, 0.0, r[index], 200, ps, rs)
返回一个数组而不是一个数字
我想补充说,对于我的另一个模型,它工作正常(它返回一个数字而不是数组):
def integrate_Burk(rx,p0,r0):
rho = (p0 * r0**3) / ( (rx + r0) * (rx**2 + r0**2) )
function_result = rho * 4.0 * np.pi * rx**2
return function_result
def chisqfuncBurk(iter_vars):
global v_model
#Normalizes p0 (p0 is too large relative to rc)
p0 = iter_vars[0] * 3.85e+09
r0 = iter_vars[1]
v_model = []
for index in range(0, am):
integral_result = simpsonsRule(integrate_Burk, 0.0, r[index], 200, p0, r0)
此外,r
是一个数字数组:
0.22
0.66
1.11
1.55
2.00
2.45
2.89
3.34
3.78
4.22
4.66
5.11
5.56
6.00
和am
是r
中的数字量(在这种情况下,我相信它是14)
如果我遗漏了任何内容或者您想要其他代码,请告诉我
编辑以下是一些复制错误的代码
from scipy.optimize import*
import numpy as np
am = 14
r = np.array([0.22,
0.66,
1.11,
1.55,
2.00,
2.45,
2.89,
3.34,
3.78,
4.22,
4.66,
5.11,
5.56,
6.00])
def simpsonsRule(func, a, b, n, p0, r0):
if n%2 == 1:
return "Not applicable"
else:
h = (b - a) / float(n)
s = func(a, p0, r0) + sum((4 if i%2 == 1 else 2) * func(a+i*h, p0, r0) for i in range(1,n)) + func(b, p0, r0)
return s*h/3.0
def integrate_NFW(rx,ps,rs):
rho = ps/((r/rs)*((1+(r/rs))**2))
function_result = rho * 4.0 * np.pi * rx**2
return function_result
def chisqfuncNFW(iter_vars):
global v_model
#Normalizes p0 (p0 is too large relative to rc)
ps = iter_vars[0] * 3.85e+09
rs = iter_vars[1]
for index in range(0, am):
integral_result = simpsonsRule(integrate_NFW, 0.0, r[index], 200, ps, rs)
print(integral_result)
initial_guess = np.array([1.0, 2.0])
resNFW = minimize(chisqfuncNFW, initial_guess,method = 'Nelder-Mead')
答案 0 :(得分:2)
您可以访问函数中的全局数组r
:
def integrate_NFW(rx,ps,rs):
rho = ps/((r/rs)*((1+(r/rs))**2))
这会将rho
变成数组。