Skip to content

Instantly share code, notes, and snippets.

@s-leroux
Last active September 7, 2017 11:58
Show Gist options
  • Save s-leroux/22620ad5409ae3f37025b74adef20e74 to your computer and use it in GitHub Desktop.
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
//
// 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");
}
}
@aleem006
Copy link

aleem006 commented Sep 7, 2017

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