我正在尝试用 Python 重现这个 Mathematica 程序:
它找到数值积分的根,并形成这些值的图。但是,我无法尝试运行。
当前尝试:
从 scipy.integrate 导入四边形 从 scipy 导入整合 从 scipy.optimize 导入 fsolve 将 pylab 导入为 pl 将 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
最佳答案
正如评论中已经提到的那样(@Hristo Iliev 和@Pavel Annosov),quad
returns 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)
提供给fsolve
,which also expects a function (一个 callable
,更准确地说)。
在稍微更一般的层面上,您不应该使用玻尔兹曼常数、hbar 等的数值(甚至 Mathematica 也会提示!)。相反,你应该做的是,你应该以无量纲形式编写你的公式:以能量单位测量温度(因此 k_B = 1)等,在积分中进行适当的替换,以便你处理无量纲参数的无量纲函数---和然后让计算机处理这些。
关于python - 求数值积分的根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15027448/