Last active
August 29, 2015 13:59
-
-
Save ykonishi/10957477 to your computer and use it in GitHub Desktop.
MC simulation code for 2D Ising model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
MC simulation code for 2-dimensional Ising model | |
Copyright (C) 2014 Yusuke Konishi | |
This software is released under the MIT License. | |
http://opensource.org/licenses/mit-license.php | |
*/ | |
package main | |
import ( | |
"fmt" | |
"math" | |
"math/rand" | |
) | |
// L is the size of the system. | |
// The number of Monte Carlo steps is mcs1+mcs2, | |
// and we use mcs2 steps for calculating magnetization. | |
var L, mcs1, mcs2 int = 100, 1000, 1000 | |
func main() { | |
// L2 is the number of spins. | |
L2 := L*L | |
spin := make([]int, L2) | |
im := make([]int, L) | |
ip := make([]int, L) | |
// using seed 100 | |
rand.Seed(100) | |
// Initially, the system has random configuration. | |
for i :=0; i < L2; i++ { | |
spin[i] = 2 * int(2*rand.Float64()) - 1 | |
} | |
// im gives i-1, ip gives i+1, 0-1 = L-1, (L-1)+1 = 0 | |
for i := 0; i < L; i++ { | |
im[i] = i-1 | |
ip[i] = i+1 | |
} | |
im[0] = L-1 | |
ip[L-1] = 0 | |
// Temperature changes from 10 to 0.1, d(temperature) = 0.1 | |
for itemp := 100; itemp > 0; itemp-- { | |
var temp, inverse_temp, mag, mag2, mag4 float64 | |
temp = float64(itemp) / 10.0 | |
inverse_temp = 1.0 / temp | |
// weight gives square of the exp(-(energy)/(temperature)) | |
w1 := math.Exp(inverse_temp * 4) | |
w2 := w1*w1 | |
var weight = map[int]float64 { | |
-4: 1.0 / w2, | |
-2: 1.0 / w1, | |
0: 1.0, | |
2: w1, | |
4: w2, | |
} | |
// Monte Carlo loop | |
mag = 0 | |
mag2 = 0 | |
mag4 = 0 | |
for time := 0; time < mcs1 + mcs2; time++ { | |
var sum_spin int = 0 | |
for i :=0; i < L2; i++ { | |
var x, y int = i/L, i%L | |
nearest_spins := spin[im[x]*L+y] + spin[ip[x]*L+y] + spin[x*L+im[y]] + spin[x*L+ip[y]] | |
if weight[nearest_spins * -spin[i]] > rand.Float64() { | |
spin[i] = -spin[i] | |
} | |
sum_spin = sum_spin + spin[i] | |
} | |
if time > mcs1 { | |
mag_tmp := float64(sum_spin) / float64(L2) | |
mag_tmp2 := mag_tmp * mag_tmp | |
mag_tmp4 := mag_tmp2 * mag_tmp2 | |
mag = mag + mag_tmp | |
mag2 = mag2 + mag_tmp2 | |
mag4 = mag4 + mag_tmp4 | |
} | |
} | |
mag = mag / float64(mcs2) | |
mag2 = mag2 / float64(mcs2) | |
mag4 = mag4 / float64(mcs2) | |
fmt.Println(temp, mag, mag2, mag4) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment