精确的Python2.7计算,包括Pi

2024-09-30 06:33:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个小程序,它计算与轨道力学有关的不同事物,例如轨道的半长轴、速度等(回答这个问题不需要这方面的经验)。你知道吗

一切都很顺利,直到我试图计算轨道周期(我必须使用π的公式):

T=2π√a3(Click for image)

其中,T是以秒为单位的时间,a是半长轴,µ是标准重力参数。你知道吗

现在,我的问题是,我的程序计算得不是很精确,因为公式的结果有点不准确;例如:在160公里高度的圆形轨道应该需要大约88分钟,但我的程序告诉我大约90分37秒。你知道吗

我的代码:

#the standard gravitational parameter of the Earth
gravPara = 3.986004418*10**14

#the semi-major axis of the orbit (the radius of the Earth + the apoapsis and periapsis of your orbit / 2)
semiMajor = (bodyDia + ap + pe) / 2

#formula to calculate orbital period
timeSeconds = (2 * math.pi) * math.sqrt(semiMajor**3 / gravPara)

#making the result appear as minutes and seconds instead of just seconds
timeMinutes = 0
while (timeSeconds > 60):
   timeSeconds = timeSeconds - 60
   timeMinutes = timeMinutes + 1

#round the variable to store seconds
round(timeSeconds, 0)

#print the result
print timeMinutes
print timeSeconds

所以我的问题是:这是我的代码中的一个错误,还是math.pi在这样的公式中一起使用时不是很精确?我应该将它存储为一个float并改用float,还是应该将计算分成多个部分?你知道吗

如果您能在这方面帮助我,我将非常感激,因为搜索Python参考资料以及其他论坛并没有让我走得很远。你知道吗

PS:当使用print math.pi时,它返回一个精确的Pi值,因此math.pi函数似乎工作正常。你知道吗


Tags: ofthe代码程序pimath公式seconds
2条回答

math.pi是一个带15位小数的浮点:3.141592653589793

根据chepners对你的原始帖子的评论,在计算地球大小的球体时,这相当于一个原子的大小。你知道吗

所以回答你的问题:它不是math.pi

好吧-似乎我找到了问题的解决方案;在编辑问题以包含变量semiMajor的计算时,我意识到我忘记在bodyDia + ap + pe周围包含括号,这导致了错误的优先级排序,导致计算不太精确。你知道吗

所以在我的代码中这只是一个愚蠢的错误,通过添加两个括号就很容易解决了。 谢谢你花时间。你知道吗

相关问题 更多 >

    热门问题