Created
July 25, 2014 04:04
-
-
Save chrislukkk/fb3d73fc268b19b122d5 to your computer and use it in GitHub Desktop.
Career cup 5.2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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