gpt4 book ai didi

c++ - 处理 0.0 和 -0.0,如何正确比较值

转载 作者:行者123 更新时间:2023-11-28 06:46:37 25 4
gpt4 key购买 nike

<分区>

我正在研究确定圆和射线是否相互相交的函数。函数的基础来自 this website具体this page .在作者讨论圆和射线相交的第一页的注释中,他列出了关于确定圆和射线是否相交的内容

The exact behavior is determined by the expression within the square root b * b - 4 * a * c

  • If this is less than 0 then the line does not intersect the sphere.

  • If it equals 0 then the line is a tangent to the sphere intersecting it at one point, namely at u = -b/2a.

  • If it is greater then 0 the line intersects the sphere at two points.

这就是我代码中的问题所在。它在于下面函数中double bb4ac 的比较。

bool CircleRayIntersect(double ip1_x, double ip1_y, double ip2_x, double ip2_y,
double isc_x, double isc_y, double isc_r,
double &out1_x, double &out1_y,
double &out2_x, double &out2_y)
{
double a,b,c;
double bb4ac;
double r = isc_r;
double dp_x;
double dp_y;
double mu_1;
double mu_2;
double p1_x = ip1_x;
double p1_y = ip1_y;
double p2_x = ip2_x;
double p2_y = ip2_y;
double sc_x = isc_x;
double sc_y = isc_y;

dp_x = p2_x - p1_x;
dp_y = p2_y - p1_y;
a = dp_x * dp_x + dp_y * dp_y;
b = 2 * (dp_x * (p1_x - sc_x) + dp_y * (p1_y - sc_y));
c = sc_x * sc_x + sc_y * sc_y ;
c += p1_x * p1_x + p1_y * p1_y;
c -= 2 * (sc_x * p1_x + sc_y * p1_y);
c -= r * r;
bb4ac = b * b - 4 * a * c;

// Checks to make sure that the line actually intersects
TRACE(" -- Checking a: %f\n", a);
TRACE(" -- Checking bb4ac: %f\n", bb4ac);

if (abs(a) < 1E-9 || bb4ac < 0.0)
{

if(bb4ac < 0.0)
{
TRACE("bb4ac is less than zero: %d < 0.0 = %d\n", bb4ac, (bb4ac < 0.0));
TRACE("bb4ac is less than zero: %f < 0.0 = %f\n", bb4ac, (bb4ac < 0.0));
}
if (abs(a) < 1E-9)
TRACE("abs(a) is less than zero\n");

mu_1 = 0;
mu_2 = 0;
TRACE("Ray does not intersect with circle!\n");
return FALSE;
}

mu_1 = (-b + sqrt(bb4ac)) / (2 * a);
mu_2 = (-b - sqrt(bb4ac)) / (2 * a);

out1_x = p1_x + (mu_1*(p2_x-p1_x));
out1_y = p1_y + (mu_1*(p2_y-p1_y));
out2_x = p1_x + (mu_2*(p2_x-p1_x));
out2_y = p1_y + (mu_2*(p2_y-p1_y));

return TRUE;
}

在某些时候,当使用某些参数调用此代码时,bb4ac 最终等于 -0.0。当发生这种情况时,bb4ac 根据上面列出的规则进行的检查将被破坏。以下是 bb4ac-0.0TRACE 语句的一些示例输出。

  -- Checking     a: 129.066667
-- Checking bb4ac: -0.000000
bb4ac is less than zero: 0 < 0.0 = -1114636288
bb4ac is less than zero: -0.000000 < 0.0 = 0.000000

TRACE 的输出来看,它看起来像是比较 bb4ac0< 的 if(..) 语句 没有正确解释 bb4ac。看到 bb4ac 在用 %d 标志解释时打印为 -1114636288 ,在用 -0.000 解释时%f 标志,我不得不认为 bb4acif 语句中被解释为 -1114636288 并且不是 -0.000

如何编写 if 语句以将 bb4ac 正确解释为 -0.000?为什么它首先看到它?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com