[英]Simpson's Rule returning an array in Python
好的,所以我的辛普森規則定義為:
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)
當您打印出integrate_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')
您可以在函數中訪問全局數組r
:
def integrate_NFW(rx,ps,rs):
rho = ps/((r/rs)*((1+(r/rs))**2))
這將rho
變成一個數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.