我正在学习和提高我的 Python 技能。
我在 Python 中做了一个关于Mandelung constant的程序。但是,我有一个问题。使用以下总和计算 Mangelung 常数:
或者
当我运行它时,它需要很长时间,当我输入一个巨大的数字时。所以,我需要改进我的代码,以更快地运行它。有人可以向我解释一种方法吗?(导入其他库,使用其他东西)
我做的代码:
import time
start_time = time.time()
L = int(input("Put the number of L:")) # size of the lattice
L = L+1 # this is for the vector (0,0,0)
# n = 0 # number of atoms
M = 0 # Madelung constant
for i in range(-L,L+1):
for j in range(-L,L+1):
for k in range(-L,L+1):
# n += 1 #counter for number of atoms
if i == j == k == 0: # doesn't count the origin (0,0,0)
continue
r = (i**2 + j**2 + k**2)**(-0.5)
if (i + j + k) % 2 == 1: # odd number
r *= -1
M += r
print ("Mandelung Constant is::", M)
print("It takes %s seconds" % (time.time() - start_time))
当我放一个, 需要超过 7 分钟。这就是我试图改进它的原因。