Given following codes:
long testNum = 1000;
double midNum = testNum/60000;
System.out.println(midNum);
long another = Math.round(7600/midNum);
System.out.println(another);
The output is:
0.0
9223372036854775807
0.0
? How could I get the right result in java?0
, why the next expression has an result? Shouldn't it throw out an by zero
expression?Why the first output is 0.0?
You are using integer division so this is the right result.
How could I get the right result in java?
Don't use integer division, use floating point instead, the simplest way to to make one of the value a floating point like this.
double midNum = testNum/60000.0;
or
double midNum = testNum/60e3;
Since the first output is 0, why the next expression has an result?
Floating point arithmetic uses IEEE-754 standard (sometimes called IEEE-753.99999999999998 ;) In floating point, you never get an exception in Java, you might get infinity, negative infinity or NaN.
Integers don't have Infinity, or NaN and have no way to represent this, so it produced an Exception.
When you round any number too big for a long
it gives you the closest presentable value which is Long.MAX_VALUE
BTW
long l = Math.round(Double.POSITIVE_INFINITY); // l == Long.MAX_VALUE
long l = Math.round(Double.NEGATIVE_INFINITY); // l == Long.MIN_VALUE
long l = (long) Double.NaN; // l == 0
From Double
you might find this interesting.
public final class Double extends Number implements Comparable<Double> {
/**
* A constant holding the positive infinity of type
* {@code double}. It is equal to the value returned by
* {@code Double.longBitsToDouble(0x7ff0000000000000L)}.
*/
public static final double POSITIVE_INFINITY = 1.0 / 0.0;
/**
* A constant holding the negative infinity of type
* {@code double}. It is equal to the value returned by
* {@code Double.longBitsToDouble(0xfff0000000000000L)}.
*/
public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
/**
* A constant holding a Not-a-Number (NaN) value of type
* {@code double}. It is equivalent to the value returned by
* {@code Double.longBitsToDouble(0x7ff8000000000000L)}.
*/
public static final double NaN = 0.0d / 0.0;
/**
* A constant holding the largest positive finite value of type
* {@code double},
* (2-2<sup>-52</sup>)·2<sup>1023</sup>. It is equal to
* the hexadecimal floating-point literal
* {@code 0x1.fffffffffffffP+1023} and also equal to
* {@code Double.longBitsToDouble(0x7fefffffffffffffL)}.
*/
public static final double MAX_VALUE = 0x1.fffffffffffffP+1023; // 1.7976931348623157e+308