我试图用C语言在opengl中建立一个太阳系的模拟。我似乎不知道如何编写计算另一颗行星所受力方向的代码。这就是我到目前为止所拥有的:
void attraction(planet self, planet other, float *direction)
{
float d = vecDistance(self.p, other.p);
//calc the force of attraction
float f = G * ((self.mass * other.mass) / (pow(d, 2)));
//calc the direction of the force
float vectorDist[3];
vecSub(self.p, other.p, vectorDist);
direction[0] = f*vectorDist[0] / d;
direction[1] = f*vectorDist[1] / d;
direction[2] = f*vectorDist[2] / d;
}
float vecDistance( float *pV1, float *pV2 )
{
float fLen=0.0f;
if(pV1 && pV2)
{
float av[3];
vecSub(pV2, pV1, av);
fLen=vecLength(av);
}
return fLen;
}
void vecSub( float *pV0, float *pV1, float *pVRes )
{
if(pV0 && pV1 && pVRes)
{
pVRes[0]=pV0[0]-pV1[0];
pVRes[1]=pV0[1]-pV1[1];
pVRes[2]=pV0[2]-pV1[2];
}
}
发布于 2016-01-08 23:22:32
如果没有输入数据,很难知道,但我猜您正遇到浮点溢出,因为您操作的值太大了。
例如,如果您的单元位于SI单元系统中,那么:
venus.mass = 4.87e+24; // kg
earth.mass = 5.98e+24; // kg
你方程式中的分子变成:
self.mass * other.mass == 2.91047e+49;
单精度floating-point numbers不能大于3.4e+38,因此质量乘积被视为无穷大.
当然,高指数在某种程度上相互抵消,因为距离也很大(按1e+10的顺序),引力常数也很小,但是如果上面的积是一个内在的结果,那么所有相关的结果都是错误的。( -1.0#IND
的意思是不确定的,对应于NaN
,而不是数字,一个无效的浮点数。)
有几种方法可以解决这个问题:
(m1 * m2) / (d*d)
,而是编写(m1 / d) * (m2 / d)
。double
而不是浮点。最大可表示的double
大约是。1.8e+308。请注意,duoble
并没有解决这个问题,它只是给了您更大的操作空间。不过,以你为例,你应该做得很好。https://stackoverflow.com/questions/34689392
复制相似问题