“1d caminata aleatoria en Python Stack Exchange” Código de respuesta

1d caminata aleatoria en Python Stack Exchange

# Python code for 1-D random walk. 
import random 
import numpy as np 
import matplotlib.pyplot as plt 

# Probability to move up or down 
prob = [0.05, 0.95]   

n = 1000 # number of steps

# statically defining the starting position 
start = 2  
positions = [start] 

# creating the random points 
rr = np.random.random(n) 
downp = rr < prob[0] 
upp = rr > prob[1] 

t = 1

step = (1/n)**0.5

for idownp, iupp in zip(downp, upp): 
    down = step if idownp and positions[-1] > 1 else 0
    up = step if iupp and positions[-1] < 4 else 0
    positions.append(positions[-1] - down + up) 

# plotting down the graph of the random walk in 1D 
x = [i*t/n for i in range(n+1)]
plt.plot(x, positions) 
plt.xlabel('Time (seconds)')
plt.ylabel('Distance')
plt.title(f"Random Walk ({n} steps in {t} seconds)")
plt.grid(True)
plt.savefig("random_walk.png")


plt.show()
Ugliest Unicorn

1d caminata aleatoria en Python Stack Exchange


# Python code for 1-D random walk. 
import random 
import numpy as np 
import matplotlib.pyplot as plt 

# Probability to move up or down 
prob = [0.05, 0.95]   

n = 1000 # number of steps

# statically defining the starting position 
start = 2  
positions = [start] 

# creating the random points 
rr = np.random.random(n) 
downp = rr < prob[0] 
upp = rr > prob[1] 

t = 1

step = (1/n)**0.5

for idownp, iupp in zip(downp, upp): 
    down = step if idownp and positions[-1] > 1 else 0
    up = step if iupp and positions[-1] < 4 else 0
    positions.append(positions[-1] - down + up) 

# plotting down the graph of the random walk in 1D 
x = [i*t/n for i in range(n+1)]
plt.plot(x, positions) 
plt.xlabel('Time (seconds)')
plt.ylabel('Distance')
plt.title(f"Random Walk ({n} steps in {t} seconds)")
plt.grid(True)
plt.savefig("random_walk.png")


plt.show() 

Kind Kitten

Respuestas similares a “1d caminata aleatoria en Python Stack Exchange”

Preguntas similares a “1d caminata aleatoria en Python Stack Exchange”

Más respuestas relacionadas con “1d caminata aleatoria en Python Stack Exchange” en Python

Explore las respuestas de código populares por idioma

Explorar otros lenguajes de código