Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horner's recursive algorithm for fractional part - Java

I am trying to create a recursive method that uses Horner's algorithm to convert a fractional number in base n to base 10. I've searched here and all over but couldn't find anywhere that dealt with the fractional part in detail. As a heads up, I'm pretty weak in recursion as I have not formally learned it in my programming classes yet, but have been assigned it by another class.

I was able to make a method that handles the integer part of the number, just not the fractional part.

I feel like the method I've written is fairly close as it gets me to double the answer for my test figures (maybe because I'm testing base 2).

The first param passed is an int array filled with the coefficients. I'm not too concerned with the order of the coefficients as I'm making all the coefficients the same to test it out.

The second param is the base. The third param is initialized to the number of coefficients minus 1 which I also used for the integer part method. I tried using the number of coefficients, but that steps out of the array.

I tried dividing by the base one more time as that would give me the right answer, but it doesn't work if I do so in the base case return statement or at the end of the final return statement.

So, when I try to convert 0.1111 base 2 to base 10, my method returns 1.875 (double the correct answer of 0.9375).

Any hints would be appreciated!

//TL;DR
coef[0] = 1; coef[1] = 1; coef[2] = 1; coef[3] = 1;
base = 2; it = 3;
//results in 1.875 instead of the correct 0.9375



public static double fracHorner(int[] coef, int base, int it) {
    if (it == 0) {
        return coef[it];
    }
    return ((float)1/base * fracHorner(coef, base, it-1)) + coef[it];
}
like image 914
Lathan Avatar asked Sep 16 '12 05:09

Lathan


1 Answers

Observe that fracHorner always returns a value at least equal to coef[it] because it either returns coef[it] or something positive added to coef[it]. Since coef[it] >= 1 in your tests, it will always return a number greater than or equal to one.

It's relatively easy to fix: divide both coef[it] by base:

public static double fracHorner(int[] coef, int base, int it) {
    if (it == 0) {
        return ((double)coef[it])/base;
    }
    return (fracHorner(coef, base, it-1) + coef[it])/base;
}
like image 189
nneonneo Avatar answered Oct 20 '22 11:10

nneonneo