T4000
T4000

Reputation: 231

My recursive function does not return the correct value

I wrote a recursive function that computes the sum of an array of double. For some reasons, the value returned by my recursive function is not correct. Actually, my recursive sum does not match my iterative sum. I know I made a little mistake somewhere, but I can't see where. Your help will be very appreciated. I only pasted the recursive function. I am using C++ on Visual Studio. Thanks!

double recursive_sum(double array_nbr[], int size_ar)
{ double rec_sum=0.0;
if( size_ar== 0) 
    return -1;
else if( size_ar> 0)
       rec_sum=array_nbr[size_ar-1]+recursive_sum(array_nbr,size_ar-1);

return  rec_sum;
}

 //####  Output######


 The random(s) number generated in the array =
 0.697653  |  0.733848  |  0.221564  |



 Recursive sum: 0.653066

 Iterative sum: 1.65307

 Press any key to continue . . .

Upvotes: 0

Views: 476

Answers (3)

Jason
Jason

Reputation: 32510

While this does not account for the large discrepancy in your output, another thing to keep in mind is the ordering of operations once you have fixed the issue with returning a -1 vs. 0 ... IEEE floating point operations are not necessarily commutative, so make sure that when you are doing your recursive vs. iterative methods, you add up the numbers in the exact same order, otherwise your output may still differ by some epsilon value.

For instance, currently in your recursive method you're adding up the values from the last member of the array in reverse to the first member of the array. That may, because of the non-commutative property of floating point math, give you a slightly different value (small epsilon) than if you sum up the values in the array from first to last. This probably won't show on a simple cout where the floating point values are truncated to a specific fixed decimal position, but should you attempt to use the == operation on the two different summations without incorporating some epsilon value, the result may still test false.

Upvotes: 0

Joker_vD
Joker_vD

Reputation: 3765

Well, because sum of no elements is zero, not minus one.

if (size_ar == 0.0)
    return 0.0;

Think about it this way: sum(1,2,3) is the same as sum(1,2) + sum(3) just as it is the same as sum(1,2,3)+sum() — in all three cases, you add 1, 2, and 3 together, just in a slighlty different ways. That's also why the product of no elements is one.

Upvotes: 4

George
George

Reputation: 2057

Try changing "if( size_ar== 0) return -1;" to return 0.

Upvotes: 1

Related Questions