我正在写一个程序,利用欧拉的方法来计算小行星的轨道是否会导致与地球的碰撞。在主循环的每次迭代结束时,都有一个if语句,它使用小行星和地球之间的距离来确定是否会发生碰撞。当我试着运行这个程序时,我得到一个溢出错误:数值结果超出范围,我假设这是由于我正在使用三角函数来转换极坐标和极坐标之外的事实,并且想知道如何限制这些函数返回的浮点值的大小以修复错误?在
编辑:以下是例外:
Traceback (most recent call last):
File "/home/austinlee/eclipse/plugins/org.python.pydev_2.7.0.2013032300/pysrc/pydevd.py", line 1397, in <module>
debugger.run(setup['file'], None, None)
File "/home/austinlee/eclipse/plugins/org.python.pydev_2.7.0.2013032300/pysrc/pydevd.py", line 1090, in run
pydev_imports.execfile(file, globals, locals) #execute the script
File "/home/austinlee/workspace/test/src/orbit.py", line 72, in <module>
if( Dist(x_a, x_e, y_a, y_e) < d_close):
File "/home/austinlee/workspace/test/src/orbit.py", line 37, in Dist
return sqrt((b-a)**2+(d-c)**2)
OverflowError: (34, 'Numerical result out of range')
代码如下:
^{pr2}$提前谢谢!在
问题出在你的Dist函数上。计算两点之间的距离时,将平方距离计算为中间值。这个中间值可以在相当大的距离内溢出。Wikipedia对这个问题及其解决方案进行了很好的讨论。简而言之,以下dist功能的替换将解决您当前的问题:
它只是一个数学上等价的函数,它避免了将平方距离作为中间值来计算。在修复了这个溢出错误之后,我又得到了两个可以使用类似技术修复的错误。我把你的重力函数改成这个:
^{pr2}$以及v\r公式:
从您的原始版本:
但是,仍然存在一些问题。一旦我做了这些更改,我就可以避免溢出错误,但是当theta_a变得太大时,cos函数中会出现域错误。如果θa是我认为的,你可以通过添加一个mod 2*pi来解决最后一个问题,如下所示:
代替:
下面是所有更改后的工作代码。我不确定这是否正确,但没有出现错误。在
相关问题 更多 >
编程相关推荐