I'm creating two functions that are supposed to emulate and return the result of f(i) = 1/1 + 1/2 + 1/3 ... 1/i. One function is recursive, and I'm testing that the recursive function functions correctly by implementing a non-recursive version of it. However, I've found that both functions are returning similar answers that are not exactly the same. Can somebody please explain why the functions are returning different values?
When I run the functions in the main method of the class to which they belong, I get the following output:
Recursive for 1000: 7.4854784
Non-Recursive for 1000: 7.4854717
Recursive for 1: 1.0
Non-Recursive for 1: 1.0
Recursive for 483: 6.758268
Non-Recursive for 483: 6.758267
Here's my code:
static float RecursiveFunction(int num){
//The num parameter represents the denominator that will be used
//The recursive function is continually called at lower increments of num
//If num is one, return 1 and do not call RecursiveFunction again
if (num == 1) {
return 1;
}
//Otherwise, return 1/num (in floating point decimal) and call RecursiveFunction with a parameter of num - 1
else {
return 1/(float)num + RecursiveFunction(num - 1);
}
}
//A Non-recursive version of RecursiveFunction that will be used to test RecursiveFunction
static float NonRecursiveFunction(int num) {
//The total variable adds up the fractions
float total = 0;
//While num is greater than zero, add 1/num to total and then subtract 1 from num
while (num > 0) {
total += 1/(float)num;
num -= 1;
}
return total;
}