我正在尝试模拟Python(我是一名物理系学生,编程并不是我最强的技能),我的内存不足。我只有4Gb
这是我的python程序:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 11 21:10:00 2021
@author: samuel
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from funciones import *
from ctes import *
gif_1d = True
gif_2d = True
agents = [w]*N
path_graf='/home/samuel/Documents/FISICA/20-21/Física de los sistemas complejos/Proyecto/Programas/imagenes/grafico/'
path_map = '/home/samuel/Documents/FISICA/20-21/Física de los sistemas complejos/Proyecto/Programas/imagenes/mapa/'
#Dimension del mapa 2d
dim = int(np.sqrt(N))
for i in range(iterations):
#tomar dos al azar
ag1, ag2 = eleccion_agentes()
#se realiza la transaccion
agents[ag1],agents[ag2] = transaccion(agents[ag1],agents[ag2])
#cada 100 iteraciones se guarda una imagen para el gif
if i%5000==0:
if gif_1d:
fig,ax = plt.subplots(figsize=(15,10))
ax.bar(range(1,N+1),agents)
ax.set_ylabel('Riqueza')
ax.set_title('Iteracion:' + str(i))
frame = f'{i}.png'
plt.savefig(path_graf + frame)
plt.close()
if gif_2d:
fig,ax = plt.subplots(figsize=(15,10))
mapa= np.reshape(np.array(agents),(dim,dim))
ax.imshow(mapa, cmap='viridis', interpolation='nearest')
ax.set_title('Iteracion:' + str(i))
frame = f'{i}.png'
plt.savefig(path_map + frame)
plt.close()
模块funciones.py
和ctes.py
分别是
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 12 19:56:51 2021
@author: samuel
"""
from ctes import *
import random
def eleccion_agentes():
iguales=True
while iguales:
x1=random.randint(0,N-1)
x2=random.randint(0,N-1)
if x1!=x2:
iguales=False
return x1, x2
#función que dados dos agentes, hace la transaccion y devuelve las nuevas riquezas
#de los mismos
def transaccion(w1,w2):
delta=random.uniform(0.0,alfa)*min(w1,w2)
if random.random() <= 0.5:
w1=w1+delta
w2=w2-delta
else:
w1=w1-delta
w2=w2+delta
return w1,w2
及
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 12 19:57:28 2021
@author: samuel
"""
iterations = int(5e7) #iterations for the simulation (number of transactions)
N=10000 #total number of agents (but we can work with the normalized distrib: N=1 and W=1)
#DEBE SER NUMERO CON RAIZ, PARA QUE EL GIF 2D SALGA BIEN.
w = 100 #units of initial wealth for each agent.
W = w*N #total wealth
alfa = 0.25 #
如前所述,问题是我的内存不足。以前,当我尝试在同一个问题中创建gif时,图像在创建时保存在列表中(每5000次迭代),但现在我只是将它们保存在某个目录中,以便在创建后制作动画。我认为这将提高RAM的使用,因为没有大的变量随着每次迭代而增加。但我仍然充满了我的记忆
我该怎么做才能不发生这种事
PD:如果Spyder环境有用的话,我正在使用它
目前没有回答
相关问题 更多 >
编程相关推荐