Write numpy code to perform monte carlo sampling for 1D classical Ising model with…
- User
Write numpy code to perform monte carlo sampling for 1D classical Ising model with magnetic field
Assistant
Here is numpy code to perform Monte Carlo sampling for the 1D Ising model with a magnetic field:
import numpy as np # Parameters J = 1.0 # Coupling constant h = 0.5 # Magnetic field T = 2.0 # Temperature # Initialize spins to random +1 or -1 spins = np.random.choice([-1, 1], size=100) # Monte Carlo steps for i in range(10000): # Pick a random spin s = np.random.randint(0, len(spins)) # Calculate energy change if we flip that spin de = 2 * J * (spins[s-1] + spins[s+1]) + 2 * h # Accept or reject the spin flip using Metropolis criterion if de <= 0 or np.random.rand() < np.exp(-de/T): spins[s] *= -1 # Compute magnetization mag = np.mean(spins)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.