我正在修我的第一门程序设计课程,这门课程是为物理应用之类的课程准备的。我们马上就要考试了,我的教授发表了一篇练习题,题目如下。你知道吗
The Maxwell distribution in speed v for an ideal gas consisting of particles of mass m at Kelvin temperature T is given by:
Stackoverflow不使用MathJax来处理公式,我也不知道如何在这个站点上编写公式。下面是WolframAlpha的链接:
where k is Boltzmann's constant, k = 1.3806503 x 10-23 J/K.
Write a Python script called maxwell.py which prints v and f(v) to standard output in two column format. For the particle mass, choose the mass of a proton, m = 1.67262158 10-27 kg. For the gas temperature, choose the temperature at the surface of the sun, T = 5778 K.
Your output should consist of 300 data points, ranging from v = 100 m/s to v = 30,000 m/s in steps of size dv = 100 m/s.
所以,这是我的代码尝试。你知道吗
import math as m
import sys
def f(v):
n = 1.67262158e-27 #kg
k = 1.3806503e-23 #J/K
T = 5778 #Kelvin
return (4*m.pi)*((n/(2*m.pi*k*T))**(3/2))*(v**2)*m.exp((-n*v**2)/(2*k*T))
v = 100 #m/s
for i in range(300):
a = float(f(v))
print (v, a)
v = v + 100
但是,我的解决方案是:
import numpy as np
def f(v):
m = 1.67262158e-27 # kg
T = 5778. # K
k = 1.3806503e-23 # J/K
return 4.*np.pi * (m/(2.*np.pi*k*T))**1.5 * v**2 * np.exp(-m*v**2/(2.*k*T))
v = np.linspace(100.,30000.,300)
fv = f(v)
vfv = zip(v,fv)
for x in vfv:
print "%5.0f %.3e"%x
# print np.sum(fv*100.)
所以,这些是非常不同的代码。据我所知,它们产生了相同的结果。我想我的问题很简单,为什么我的代码不正确?你知道吗
谢谢你!你知道吗
编辑:
所以,我问了我的教授,这是他的回答。你知道吗
I think your code is fine. It would run much faster using numpy, but the problem didn't specify that you needed numpy. I might have docked one point for not looping through a list of v's (your variable i doesn't do anything). Also, you should have used v += 100. Almost, these two things together would have been one point out of 10.
第一:有没有更好的语法来处理我的代码中的范围,因为我的变量i什么都不做?你知道吗
第二:v+=100的目的是什么?你知道吗
处理数字时要注意的是从浮点到整数的隐式类型转换。 我可以在代码中找到的一个例子是,您使用的(3/2)计算结果为1,而另一个代码直接使用1.5。你知道吗
相关问题 更多 >
编程相关推荐