Scipy odeint 意外结果

计算科学 scipy 一体化
2021-12-23 08:58:36

我正在尝试对方程进行数值积分

dPdr=(P+ρ(r))m(r)+4πr3Pr[r2m(r)]
去寻找P(r). 我已经定义了以下内容:
ρ(r)=ρc[1(rR)2]
m(r)=4πρc(5r3R23r5)15R2.
我的代码如下:

import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint

def dP_dr(x, r):
    return -(x+density(r, p_c, R))*(mass(r, p_c, R)+4*np.pi*r**3*x)/(r*(r- 
        2*mass(r, p_c, R)))

def mass(r, p_c, R):
    return 4*np.pi*p_c*(5*r**3*R**2-3*r**5)/(15*R**2)

def density(r, p_c, R):
    return p_c*(1-(r/R)**2)

p_c = 7*10**17      #central density
P_c = 1.6*10**34    #central pressure
R = 10              #radius

deltaR = 0.01
r = np.linspace(deltaR, R, int(R/deltaR))

P = odeint(dP_dr, P_c, r)

plt.figure()
plt.plot(r, P, label='Pressure')
plt.xlabel('Radius (km)')
plt.title('Neutron Star')
plt.legend(loc=0)
plt.show()

我不确定出了什么问题,但我收到了溢出错误。图表结果也是垃圾。压力,P(r)也应该减少r,但它会以非常尖锐的尖峰跳跃。对我做错的任何帮助将不胜感激。

1个回答

我已将您的代码更改为此

import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint

def dP_dr(P, r, p_c, R, G, c):
    return - G * (P + density(r, p_c, R) / c**2) * (mass(r, p_c, R) 
             + 4 * np.pi * r**3 * P / c**2) / (r * (r - 2 * G* mass(r, p_c, R) / c**2))

def mass(r, p_c, R):
    return 4 * np.pi * p_c * (5 * r**3 * R**2 - 3 * r**5) / (15 * R**2)

def density(r, p_c, R):
    return p_c * (1 - (r/R)**2)

p_c = 7 * 10**10     #central density
P_c = 1.6 * 10**15    #central pressure
R = 10              #radius
c = 3 * 10**8
G = 6.674 * 10**(-11)


deltaR = 0.0001
r = np.linspace(deltaR, R, int(R/deltaR))

P, dic = odeint(dP_dr, P_c, r, args=(p_c, R, G, c), full_output=True, printmessg=True)

num = 10000
plt.figure()
plt.plot(r[:num], P[:num], label='Pressure')
plt.xlabel('Radius (km)')
plt.title('Neutron Star')
plt.legend()
plt.show()

你必须玩num, p_c, P_c用你显示的数字,P(r)衰减非常快。顺便说一句,我在函数中添加了两个常量dP_drGc.