I've been working on an egyptian fraction program and for some reason I cant seem to figure out a way to fix this rounding error. An egyptian fraction is a fraction that can be expressed as a sum of fractions eg. 3/4 = 1/2 + 1/4. For some reason on certain fractions it rounds up and skips the correct fraction to subtract. When I run 2/7 its supposed to equal 1/4 + 1/28, but gives me 1/4 + 1/29 and decides to round. This is my code for the problem.
public class EgyptianFraction{
private static double epsilon = 1.0e-7;
public static void main(String args[]){
greedySearch(2.0/7.0);
}
public static void greedySearch(double fraction){
for(int i = 2; fraction > epsilon; i++){
if(fraction - (1.0/i) >= 0){
fraction -= (1.0/i);
}
}
}
//*****Output******
//0.0357142857142857 - 0.03571428571428571 = -1.3877787807814457E-17
}
When I print out all of the math involved it says that it gives the output above. They are fairly close but for some reason it makes the 1/28 bigger then the current fraction. The program should subtract 1/28 and then the fraction should be close enough to 0 and end. Is there any way you guys can think of to fix this problem?