2017-04-18 187 views
0

我需要一些快速帮助来绘制我为代码获得的答案。我对此很新,但是,我试图计算出计算结果的标准偏差,之后我需要绘制刚刚在图形中执行的标准偏差计算的新答案。问题是在执行计算之前出现的图只是给出一个空的图,然后考虑到代码的运行。任何帮助将不胜感激。标准偏差Python绘图

from numpy import zeros 
from random import choice, random 
import math 

def create_lattice(nx,ny): 
    possibleSpins = (-1,1) 
    lattice = zeros((nx,ny)) 
    for i in range(nx): 
     for j in range(ny): 
      lattice[i][j] = choice(possibleSpins) 
    return lattice 

def magnetization(nx, ny, lattice): 
    magnet = 0.0 
    for i in range(nx): 
     for j in range(ny): 
      magnet += (lattice[i][j]/(nx*ny)) 
    return magnet 

def ising_model(nsweeps, nx, ny, Js): 
    magnet = 0.0 
    s_energy = 0.0 
    e_energy = 0.0 
    d_energy = 0.0 
    spin = 0.0 
    rand = 0.0 
    good = 0.0 
    bad = 0.0 
    nostep = 0.0 
    lattice = create_lattice(nx, ny) 
    magnet = magnetization(nx, ny, lattice) 
    energies = zeros((nx,ny)) 
    print(lattice) 
    # Each sweep is a complete look at the lattice 
    for sweeps in range(nsweeps): 
     for i in range(nx): 
      for j in range(ny): 
       spin = lattice[i][j] 
       s_energy = -1 * Js * spin * (lattice[(i-1)][j] + lattice[i][(j-1)] + lattice[i][(j+1)%ny] + lattice[(i+1)%nx][j]) 
       lattice[i][j] = -1 * spin 
       e_energy = -1 * Js * lattice[i][j] * (lattice[(i-1)][j] + lattice[i][(j-1)] + lattice[i][(j+1)%ny] + lattice[(i+1)%nx][j]) 
       d_energy = e_energy - s_energy 
       rand = random() 
       if d_energy <= 0 : 
        good = good + 1 
        magnet += ((-2*spin)/(nx*ny)) 
        answers.append(magnet) 
       elif d_energy > 0 and rand <= math.exp(-1 * d_energy): 
        bad = bad + 1 
        magnet += ((-2*spin)/(nx*ny)) 
        answers.append(magnet) 
       else: 
        lattice[i][j] = spin 
        nostep = nostep + 1 
       print(magnet)  
    print(lattice) 
    print(good) 
    print(bad) 
    print(nostep) 
    # energies array is 
    return energies 

answers = [] 
stdofmag = [] 
def standard_deviation(): 
    stdmag = statistics.stdev(answers) 
    print(stdmag) 
    stdofmag.append(stdmag) 

import matplotlib.pyplot as plt 

fig, ax = plt.subplots() 
ax.plot(stdofmag, 'r-', label = "Std of Magnetization") 
title_temp = "Magnetization" 
plt.title(title_temp, fontsize=12, fontweight='bold', color='green') 
ax.legend(loc='best', ncol=1, fancybox=True, shadow=True) 
plt.xlabel('Number of Iterations') 
plt.ylabel('Answer') 
ax.grid(True) 
plt.show(block=True) 

不考虑x和y标签他们是虚拟变量。

回答

1

stdofmag您的stdofmag变量是一个空的列表,所以你没有绘制任何东西。你写的脚本实际上并没有做任何工作,除了创建一个图形设置一些标签并显示它。您需要实际调用您定义的函数才能填充您的列表。这就是说,我可以看到许多其他错误,将阻止这些功能的工作,因为你可能打算。可能是一个好主意,退后一步,并确保每个功能都按照您的意图进行操作,然后再尝试连接所有内容。

2

你从来没有叫standard_deviation功能,从而stdofmag=[]是空的列表,当你把它传递给plot