Skip to content

Instantly share code, notes, and snippets.

@chrislukkk
Created July 25, 2014 04:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrislukkk/fb3d73fc268b19b122d5 to your computer and use it in GitHub Desktop.
Save chrislukkk/fb3d73fc268b19b122d5 to your computer and use it in GitHub Desktop.
Career cup 5.2
package Chapter5;
public class DecimalRepr {
private static double ROUND_ERR = 0.0000000001;
public static void printBinary(double realNum) {
if(realNum >= 1 || realNum <= 0) return;
StringBuilder repr = new StringBuilder();
repr.append("0.");
double m = 0.5;
int bit = 0;
//What is the definition of "accurately"?
//careful double round error
while(realNum - 0 >= ROUND_ERR) {
if(bit >= 32) {
//System.out.println("ERROR");
System.out.println("ERROR");
return;
}
if(realNum >= m) {
repr.append('1');
realNum -= m;
} else
repr.append('0');
m *= 0.5;
bit++;
}
System.out.println(repr.toString());
}
public static void main(String[] args) {
printBinary(0.75);
printBinary(0.72);
printBinary(0.61);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment