我有以下的遞歸代碼,並沒有像預期的那樣(詳見下文):C++遞歸誤差
R3Intersection ComputeIntersectionNode(R3Ray *ray, R3Node *node)
{
R3Intersection closest_inter;
R3Intersection child_inter;
R3Intersection shape_inter;
double least_t = DBL_MAX;
// check for intersection with shape
if(node->shape != NULL)
{
shape_inter = ComputeIntersectionShape(ray, node->shape);
if(shape_inter.hit == 1)
closest_inter = shape_inter;
}
// go through all the children and for each child, compute
// the closest intersection with ray
for(int i = 0; i < node->children.size(); i++)
{
// compute intersection with children[i] and ray
child_inter = ComputeIntersectionNode(ray, node->children[i]);
// if there's an intersection with the child node and
// it is the closest intersection, set closest intersection
if(child_inter.hit == 1 && fabs(child_inter.t) < fabs(least_t))
closest_inter = child_inter;
}
return closest_inter;
}
這ComputeIntersectionNode(...)
,除了遞歸調用,也被稱爲多線在節目中。爲了測試這個功能,我運行它4 rays
和4 nodes
(或更準確地說,node
類型的一個root
,它沒有shape
,但有4個children
,其中每個都有一個shape
)。爲了測試,每個ray
恰好相交一個node
/shape
。
當我運行在GDB代碼用於第一ray
,它首先通過root
通過代碼,其不具有shape
,所以把它直接轉到children
。它正確地計算第一個孩子的路口,並設置closest_inter
變量正確,以及作爲closest_inter
與child_inter.hit = 1;
然後,第二個孩子被處理這裏設置它獲取返回遞歸和child_inter
的最高水平爲好。 ComputeIntersectionShape(...)
返回與第二個孩子沒有交集(shape_inter.hit == 0
;) - 這是預期的行爲。但是,當函數返回到遞歸的最高級別時,出於某種原因child_inter.hit被設置爲1(但應設置爲0)。
有什麼建議嗎?
預先感謝您。
你是否在'for'循環中缺少'break'? – atlpeg 2010-03-31 20:33:29
R3Intersection默認構造函數是否顯式初始化了hit? – 2010-03-31 21:04:42
@atlpeg:我不希望打破,一旦我找到了交集,因爲我想找到最近的交點,所以我必須遍歷所有兒童 – Myx 2010-03-31 22:17:21