用swendsen-wang 算法模拟2D Ising模型的图片
时间: 2024-06-08 07:10:56 浏览: 17
很抱歉,作为AI助手,我没有图像生成的能力,但我可以为您提供Swendsen-Wang算法模拟2D Ising模型的Python代码示例,您可以自行运行并生成图片。
```python
import numpy as np
import matplotlib.pyplot as plt
def initialize_lattice(N):
"""
初始化晶格
"""
lattice = np.random.choice([-1, 1], size=(N, N))
return lattice
def calculate_energy(lattice):
"""
计算晶格的总能量
"""
energy = 0
N = lattice.shape[0]
for i in range(N):
for j in range(N):
spin = lattice[i, j]
nb_sum = lattice[(i+1)%N, j] + lattice[i, (j+1)%N] + lattice[(i-1)%N, j] + lattice[i, (j-1)%N]
energy += -nb_sum*spin
return energy/4
def swendsen_wang(lattice, beta):
"""
Swendsen-Wang 算法模拟2D Ising模型
"""
N = lattice.shape[0]
cluster = np.zeros((N,N))
p = 1 - np.exp(-2*beta)
# 构建簇
for i in range(N):
for j in range(N):
if cluster[i,j] == 0:
cluster[i,j] = 1
stack = [(i,j)]
while stack:
site = stack.pop()
nb_sites = [(site[0]+1, site[1]), (site[0]-1, site[1]), (site[0], site[1]+1), (site[0], site[1]-1)]
for nb in nb_sites:
if cluster[nb[0]%N, nb[1]%N] == 0 and lattice[nb[0]%N, nb[1]%N] == lattice[site[0], site[1]]:
if np.random.uniform(0,1) < p:
cluster[nb[0]%N, nb[1]%N] = 1
stack.append((nb[0]%N, nb[1]%N))
# 翻转簇中的自旋
for i in range(N):
for j in range(N):
if cluster[i,j] == 1:
lattice[i,j] = -lattice[i,j]
return lattice
# 参数设置
N = 100
T = np.linspace(1.5, 3.5, num=15)
beta = 1/T
nsteps = 2000
# 初始化晶格
lattice = initialize_lattice(N)
# 模拟
for t in range(len(T)):
E_avg = []
lattice = initialize_lattice(N)
for step in range(nsteps):
lattice = swendsen_wang(lattice, beta[t])
E_avg.append(calculate_energy(lattice))
plt.hist(E_avg, bins='auto', alpha=0.5, density=True, label=f'T={T[t]:.1f}')
# 图像绘制
plt.xlabel('能量')
plt.ylabel('概率密度')
plt.title('2D Ising模型')
plt.legend()
plt.show()
```
运行上述代码,会得到一个由多张能量分布图组成的图像,每张图对应一个温度。您可以根据需要修改代码中的参数并运行,以生成符合您需求的图像。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)