python - 用于伊辛模型的 python 中的嵌套循环

标签 python python-3.x physics enumeration

我目前正在研究统计力学,并尝试对其应用一些编程,因为它们非常适合!我正在努力寻找有限数量粒子的配分函数。然而..分区函数被定义为一个总和的总和!我想我们可以把它写成一个列表的列表,所以我们会使用嵌套的 for 循环,但我只是想不出正确的写法。

Z=\sum_{s_1}^{s_N}e^(s_1s_2+...+s_(N-1)s_N) 是配分函数。

enter image description here

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 解决方案可能更快,假设您想为许多状态计算 Znumpy 实现会开始遇到内存问题,而生成器表达式不会:

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/

相关文章:

python - 构建:使用来自系统 Python 的依赖项

python - 找到多项式曲线之间交点的有效方法?

python - 在Python中对对象应用函数

python - 如何在 python 3 中将复杂的数据帧值转换为 float ?

c - 3D 网格的 Morton 逆向编码

rotation - 如何旋转圆来响应碰撞?

java - body 在撞墙时失去了一个速度分量

python - 将 pandas DataFrame 转换为 dict 并保留重复索引

python - 如何更改变量中存在的路径字符串(作为循环的一部分)?

python-3.x - PyDub:无法正确将文件保存在其他目录中