我目前正在研究统计力学,并尝试对其应用一些编程,因为它们非常适合!我正在努力寻找有限数量粒子的配分函数。然而..分区函数被定义为一个总和的总和!我想我们可以把它写成一个列表的列表,所以我们会使用嵌套的 for 循环,但我只是想不出正确的写法。
Z=\sum_{s_1}^{s_N}e^(s_1s_2+...+s_(N-1)s_N) 是配分函数。
s_i 的可能值为 -1,+1。
实际上,ising 模型 (1D) 是一个有 N 个点的链,每个点可以有 s_i=-1 或 +1。系统的能量取决于 s_i 的值,每种可能的组合称为状态。这些状态的总和称为 Z,配分函数。
那么对于长度为 N=5 的链(因此有 2^5=32 个可能的状态),我将如何计算这个 Z?我真的没有任何代码可以显示,但我从公式中知道结果应该类似于 e^(+1+1+1+1+1)+e^(-1+1+1+1+1) +...+e^(-1-1-1-1-1)。问题是……我到底该怎么做?我生成了一组可能的状态:
import itertools
counting=0
for state in itertools.product([1,-1],repeat=5):
print(state)
counting+=1
print('the total possible number of states is',counting).
但是我如何使用它来获得 Z 的值?
最佳答案
我会使用一个函数来计算每个状态的总和,然后再计算总和:
import itertools
from math import exp
def each_state(products):
for state in products:
yield sum(state)
Z = sum(exp(x) for x in each_state(itertools.product([1,-1],repeat=5)))
这种方法的好处是它符合 itertools
的精神:不要一次将所有内容聚合到内存中。因此,虽然 numpy
解决方案可能更快,假设您想为许多状态计算 Z
,numpy
实现会开始遇到内存问题,而生成器表达式不会:
from itertools import product
import numpy as np
from math import exp
# this will yield a single number, and product will yield
# each state one at a time, never aggregating the
# full set of objects into memory (even though it might seem slow)
x = sum(exp(sum(x)) for x in product([1,-1], repeat=500))
# On my 16GB MacBook, this process will be killed because
# we collect all of the states into memory
x = np.array(list(product([1, -1], repeat=500))
[1] 7743 killed python
一般的经验法则是 list(giant_iterable)
会用完空间,而 for item in giant_iterable
会用完时间
关于python - 用于伊辛模型的 python 中的嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53227497/