求数值积分的根

2024-09-28 22:14:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用Python复制这个Mathematica程序:

Mathematica program

它找到数值积分的根,并形成这些数值的图。然而,我无法尝试逃跑。在

当前尝试:

从整合导入四边形 从scipy导入集成 从scipy.optimize公司导入F溶剂 pylab进口 将numpy作为np导入

# Variables.
boltzmann_const = 1.38e-23
planck_const = 6.62e-34
hbar = planck_const / ( 2 * np.pi )
transition_temp = 9.2
gap_energy_at_zero_kelvin = 3.528 / ( 2 * transition_temp * boltzmann_const )
debye_freq = ( 296 * boltzmann_const ) / hbar

# For subtracting from root_of_integral
a_const = np.log( ( 1.13 * hbar * debye_freq ) / ( boltzmann_const * transition_temp) )
# For simplifying function f.
b_const = ( hbar * debye_freq ) / ( 2 * boltzmann_const)


def f( coherence_length, temp ):
    # Defines the equation whose integral will have its roots found. Epsilon = coherence length. Delta = Gap energy.

    squareRoot = np.sqrt( coherence_length*coherence_length + gap_energy*gap_energy )
    return np.tanh( ( ( b_const / temp ) * squareRoot ) / squareRoot )


def integrate( coherence_length, temp ):
    # Integrates equation f with respect to E, between 0 and 1. 

    return integrate.quad( f, 0, 1, args = ( temp, ) )[0]


def root_of_integral( temp ):
    # Finds the roots of the integral with a guess of 0.01.

   return fsolve( integrate, 0.01, args = ( temp, ) )


def gap_energy_values( temp ):
    # Subtracts a_const from each root found, to obtain the gap_energy_values.

    return root_of_integral( temp ) - a_const

Tags: ofthereturndefnprootlengthtemp
2条回答

正如@Hristo Iliev和@Pavel Annosov在评论中已经提到的,quadreturns a tuple of stuff。如果你假设积分没有问题,就像你在Mathematica中所做的那样(这不是一个好主意),那么你只需要第一个元素,它应该是积分的结果。在

但这只会给你一个数字,而不是T的函数。要获得后者,您需要自己定义相应的函数,就像在Mathematica中使用\Delta[T_]:=...所做的那样

以下是一些可以让你开始的地方:

def f(E, T):
    """To be integrated over T."""
    temp = np.sqrt(E * E + T * T)
    return np.tanh(1477.92 * temp) / temp


def gap(T):
    """Integration result: \Delta(T)"""
    return quad(f, 0, 1, args=(T, ))[0]  #NB: [0] select the 1st element of a tuple

请注意,您需要使用args=(T,)语法将T参数发送给正在集成的函数:quad对函数的第一个参数进行积分,并且它需要其他参数来计算f(E, T)。在

现在您可以将这个gap(T)提供给fsolvewhich also expects a function(更准确地说是callable)。在

在更一般的层面上,您不应该使用Boltzmann常数、hbar等数值(甚至Mathematica也抱怨过!)。相反,你应该用无量纲的形式写出你的公式:用能量单位测量温度(因此k_B=1),等等,在积分中做适当的代换,这样你就可以处理无量纲参数的无量纲函数,然后让计算机来处理。在

这条线:

integral = (integrate.quad(lambda E: np.tanh(1477.92*np.sqrt(E**2+x**2))/np.sqrt(E**2+x**2), 0, 1)

括号不平衡:

^{pr2}$

如果你把它拆散了会容易得多

^{3}$

相关问题 更多 >