在此代码中,来自pressure命令的变量[float(n) for n in line.split()]和enthalpy不会被读取到函数中:
import numpy as np
pressure_gibbs = open('pressure_gibbs_all_points.dat', 'w')
pressure_gibbs.write('#pressure gibbs\n')
## FUNCTIONS:
def G(H,S):
# G = H - TS
# Then:
gibbs = H - 298.15 * S/4.0
return gibbs
with open('entropies_parsed.dat') as entropies_parsed, open('pressure_enthalpy_all_points.dat') as enthalpy_pressure: # open the file
entropies_parsed.next() # skip the first line
enthalpy_pressure.next()
entropy = [float(line) for line in entropies_parsed]
#print entropy
for line in enthalpy_pressure:
#print entropy
pressure, enthalpy = [float(n) for n in line.split()]
#print pressure
#print enthalpy
for i in entropy:
#print i
gibbs = G(enthalpy, i)
#print gibbs
pressure_gibbs.write('{}\t{}\n'.format (pressure, gibbs))
pressure_gibbs.close()在这个文件夹中只有两个文件是运行此代码所必需的:
pressure_enthalpy_all_points.dat:
# pressure enthalpy
2 3
5 4
3.5 2entropies_parsed.dat:
# entropies
0.5
0.2
0.47 这是我所能达到的最好成绩,据我所知,压痕位置是正确的。
但是,--这段代码提供了一个文件,pressure_gibbs_all_points.dat
#pressure gibbs
2.0 -34.26875
2.0 -11.9075
2.0 -32.032625
5.0 -33.26875
5.0 -10.9075
5.0 -31.032625
3.5 -35.26875
3.5 -12.9075
3.5 -33.032625这是错误的。
如果你能帮帮我,我会很感激的。
发布于 2016-06-28 18:35:45
您的输出文件似乎显示了与代码中的数学值相匹配的值,所以我唯一能看到的是,在您期望3的地方有9次计算。这是因为您有一个嵌套的循环,所以您首先在压力上循环,然后在熵上循环。在p= 2.0,然后p= 5.0,最后是p= 3.5,计算出3个熵值的Gibbs,所以你有9次计算。如果您只需要3次计算:
for i, line in zip(entropy, enthalpy_pressure):
#print entropy
pressure, enthalpy = [float(n) for n in line.split()]
#print pressure
#print enthalpy
#print i
gibbs = G(enthalpy, i)
#print gibbs
pressure_gibbs.write('{}\t{}\n'.format (pressure, gibbs))发布于 2016-06-30 19:54:44
我认为是时候再深入研究一下numpy了,以及为什么numpy和python的组合很棒。这段代码完成了你要找的东西。这里有很多,所以你得花时间消化它。我创建了一个新的答案,因为最初的答案对您的第一个问题有详细的说明,但是下面的代码是您应该如何做到的。如果您有错误,请确保您正在为分隔符等输入正确的值。
import numpy as np
# read in the data, and tranpose the columns into rows for easy unpacking
entropy = np.loadtxt('entropies_parsed.dat', skiprows=1).T
enthalpy, pressure = np.loadtxt('pressure_enthalpy_all_points.dat', skiprows=1).T
gibbs = enthalpy - 298.15 * entropy / 4.0
# stack the data together into a new, 2-row array, and then transpose back into column format for file writing
output_array = np.vstack((pressure, gibbs)).T
np.savetxt('pressure_gibbs_all_points.dat', output_array, header="pressure\tgibbs", fmt="%0.06g")https://stackoverflow.com/questions/38083454
复制相似问题