Last active
September 7, 2017 11:58
-
-
Save s-leroux/22620ad5409ae3f37025b74adef20e74 to your computer and use it in GitHub Desktop.
Demonstration of potential issue when comparing floating point numbers and integer numbers in java
This file contains hidden or 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
| // | |
| // Tested with openjdk-8 | |
| // | |
| // Usage: | |
| // javac Surprise.java | |
| // java Surprise | |
| // | |
| public class Surprise { | |
| public static void main(String args[]) { | |
| long n = Integer.MAX_VALUE; | |
| n = n*n; | |
| long m = n+1; | |
| // n is a "large" integer | |
| // m is n+1 | |
| double d = n; | |
| // now, d *should* hold the same value as n | |
| // but... | |
| System.out.println((d==n) ? "EQUAL" : "NOT EQUAL"); | |
| System.out.println((d==m) ? "EQUAL" : "NOT EQUAL"); | |
| } | |
| } | |
well isn't it should be only equal for d==n?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
long n = Integer.MAX_VALUE; /// ????