I have come across with the following two codes. Why does it not throw an exception for floating point where as in other case it will throw a runtime exception.
class FloatingPoint
{
public static void main(String [] args)
{
float a=1000f;
float b=a/0;
System.out.println("b=" +b);
}
}
OUTPUT:b=Infinity.
If I try with int values then it will throw a runtime exception.
Why is it like this?
The short answer
Integral types (JLS 4.2.1) are categorically different from floating point types (JLS 4.2.3). There may be similarities in behavior and operations, but there are also characteristically distinguishing differences such that confusing the two can lead to many pitfalls.
The difference in behavior upon division by zero is just one of these differences. Thus, the short answer is that Java behaves this way because the language says so.
On integral and floating point values
The values of the integral types are integers in the following ranges:
byte: from -128 to 127, inclusive, i.e. [-27, 27-1]
short: from -32768 to 32767, inclusive, i.e. [-215, 215-1]
int: from -2147483648 to 2147483647, inclusive, i.e. [-231, 231-1]
long: from -9223372036854775808 to 9223372036854775807, inclusive, i.e. [-263, 263-1]
char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535, i.e. [0, 216-1]
The floating-point types are float and double, which are conceptually associated with the single-precision 32-bit and double-precision 64-bit format IEEE 754 values and operations.
Their values are ordered as follows, from smallest to greatest:
negative infinity,
negative finite nonzero values,
positive and negative zero (i.e. 0.0 == -0.0),
positive finite nonzero values, and
positive infinity.
Additionally, there are special Not-a-Number (NaN) values, which are unordered. This means that if either (or both!) operand is NaN:
numerical comparison operators <, <=, >, and >= return false
numerical equality operator == returns false
numerical inequality operator != returns true
In particular, x != x is true if and only if x is NaN.
For e.g. double, the infinities and NaN can be referred to as:
Double.POSITIVE_INFINITY
Double.NEGATIVE_INFINITY
Double.NaN, testable with helper method boolean isNaN(double)
The situation is analogous with float and Float.
On when exceptions may be thrown
Numerical operations may only throw an Exception in these cases:
NullPointerException, if unboxing conversion of a null reference is required
ArithmeticException, if the right hand side is zero for integer divide/remainder operations
OutOfMemoryError, if boxing conversion is required and there is not sufficient memory
They are ordered by importance, with regards to being common source for pitfalls. Generally speaking:
Be especially careful with box types, as just like all other reference types, they may be null
Be especially careful with the right hand side of an integer division/remainder operations
Arithmetic overflow/underflow DOES NOT cause an exception to be thrown
Loss of precision DOES NOT cause an exception to be thrown
A mathematically indefinite floating point operation DOES NOT cause an exception to be thrown
On division by zero
For integer operation:
Division and remainder operations throws ArithmeticException if the right hand side is zero
For floating point operation:
If the left operand is NaN or 0, the result is NaN.
If the operation is division, it overflows and the result is a signed infinity
If the operation is remainder, the result is NaN
The general rule for all floating point operation is as follows:
An operation that overflows produces a signed infinity.
An operation that underflows produces a denormalized value or a signed zero.
An operation that has no mathematically definite result produces NaN.
All numeric operations with NaN as an operand produce NaN as a result.
Appendix
There are still many issues not covered by this already long answer, but readers are encouraged to browse related questions and referenced materials.
Related questions
What do these three special floating-point values mean: positive infinity, negative infinity, NaN?
In Java what does NaN mean.
When can Java produce a NaN (with specific code question)
Why does (360 / 24) / 60 = 0 … in Java (distinguish integer vs floating point operations!)
Why null == 0 throws NullPointerException in Java? (beware the danger of boxed primitives!)
Is 1/0 a legal Java expression? (absolutely!!!)
Because floats actually have a representation for the "number" you're trying to calculate. So it uses that. An integer has no such representation.
Java (mostly) follows IEEE754 for its floating point support, see here for more details.
It is because integer arithmetic always wraps it's result except for the case of (Division/Remainder By Zero).
In case of float, when there is an overflow or underflow, the wrapping goes to 0, infinity or NaN.
During the overflow, it gives infinity and during underflow, it gives 0.
Again there are positive & negative overflow/underflow.
Try:
float a = -1000;
float b = a/0;
System.out.println("b=" +b);
This gives a negative overflow
Output
b=-Infinity
Similarly positive underflow will result in 0 and negative underflow in -0.
Certain operations can also result in returning a NaN(Not a Number) by float/double.
For eg:
float a = -1000;
double b = Math.sqrt(a);
System.out.println("b=" +b);
Output
b=NaN
It's a programming and math standard for representing / by zero values. float has support for representing such values in JAVA. int (integer) data type doesn't have way to represent same in JAVA.
Check :
http://en.wikipedia.org/wiki/Division_by_zero
http://www.math.utah.edu/~pa/math/0by0.html
Related
This question already has answers here:
Difference between Infinity and NaN (Not a number)
(3 answers)
Closed 5 years ago.
Can anyone explain why the flag value is returning False?
double a = 1.0;
double b = 0.0;
double c = a / b;
boolean flag = Double.isNaN(c);
System.out.println(flag); // False?
System.out.println(c); // Infinity
This is due to the definition of floating-point representation in the IEEE 754 standard. The standard has representations for both "infinity" and "NaN". "Infinity" is for operations that either produce an infinite result (such as 1/0 or tan(pi/2) [*]) or produce a result whose absolute value is larger than the largest possible number the format can represent. More precisely, in math, there really isn't such a thing as an infinite result; rather, it's defined in terms of limits. Thus, 1/0 doesn't exist, but the limit of 1/x as x approaches 0 is infinite.
NaN is returned for "indeterminate forms". In math, these are cases such as 0/0 when the limit can't be determined just by looking at the numerator and denominator. (If you have two functions f(x) and g(x) where the values are both 0 at some point f(a)=g(a)=0, then you can't determine the limit of f(x)/g(x) as x approaches a, without extra work such as L'Hopital's rule.) NaN is also returned for things like taking the square root of a negative number.
In Java, isNan returns true only for actual NaN's, not for infinities. Even though infinity really is "not a number", it doesn't meet the definition of a NaN according to the IEEE standard.
See here for a definition of which operations generate NaN.
[*] Note that "pi" can't be represented exactly in a floating-point number, so this really isn't an operation that could produce an "infinite result" on a computer.
That's what the IEEE-754 standard says. When you divide a non-zero floating point number by zero, it does not return a number, but infinity.
Take a look at this: http://grouper.ieee.org/groups/754/faq.html#exceptions
How come a primitive float value can be -0.0? What does that mean?
Can I cancel that feature?
When I have:
float fl;
Then fl == -0.0 returns true and so does fl == 0. But when I print it, it prints -0.0.
Because Java uses the IEEE Standard for Floating-Point Arithmetic (IEEE 754) which defines -0.0 and when it should be used.
The smallest number representable has no 1 bit in the subnormal significand and is called the positive or negative zero as determined by the sign. It actually represents a rounding to zero of numbers in the range between zero and the smallest representable non-zero number of the same sign, which is why it has a sign, and why its reciprocal +Inf or -Inf also has a sign.
You can get around your specific problem by adding 0.0
e.g.
Double.toString(value + 0.0);
See: Java Floating-Point Number Intricacies
Operations Involving Negative Zero
...
(-0.0) + 0.0 -> 0.0
-
"-0.0" is produced when a floating-point operation results in a negative floating-point number so close to 0 that it cannot be represented normally.
how come a primitive float value can be -0.0?
floating point numbers are stored in memory using the IEEE 754 standard meaning that there could be rounding errors. You could never be able to store a floating point number of infinite precision with finite resources.
You should never test if a floating point number == to some other, i.e. never write code like this:
if (a == b)
where a and b are floats. Due to rounding errors those two numbers might be stored as different values in memory.
You should define a precision you want to work with:
private final static double EPSILON = 0.00001;
and then test against the precision you need
if (Math.abs(a - b) < epsilon)
So in your case if you want to test that a floating point number equals to zero in the given precision:
if (Math.abs(a) < epsilon)
And if you want to format the numbers when outputting them in the GUI you may take a look at the following article and the NumberFormat class.
The floating point type in Java is described in the JLS: 4.2.3 Floating-Point Types, Formats, and Values.
It talks about these special values:
(...) Each of the four value sets includes not only the finite nonzero values that are ascribed to it above, but also NaN values and the four values positive zero, negative zero, positive infinity, and negative infinity. (...)
And has some important notes about them:
Positive zero and negative zero compare equal; thus the result of the expression 0.0==-0.0 is true and the result of 0.0>-0.0 is false. But other operations can distinguish positive and negative zero; for example, 1.0/0.0 has the value positive infinity, while the value of 1.0/-0.0 is negative infinity.
You can't "cancel" that feature, it's part of how the floats work.
For more about negative zero, have a look at the Signed zero Wikipedia entry.
If you want to check what "kind" of zero you have, you can use the fact that:
(new Float(0.0)).equals(new Float(-0.0))
is false (but indeed, 0.0 == -0.0).
Have a look here for more of this: Java Floating-Point Number Intricacies.
From wikipedia
The IEEE 754 standard for floating point arithmetic (presently used by
most computers and programming languages that support floating point
numbers) requires both +0 and −0. The zeroes can be considered as a
variant of the extended real number line such that 1/−0 = −∞ and 1/+0
= +∞, division by zero is only undefined for ±0/±0 and ±∞/±∞.
I don't think you can or need to cancel that feature. You must not compare floating point numbers with == because of precision errors anyway.
A good article on how float point numbers are managed in java / computers.
http://www.artima.com/underthehood/floating.html
btw: it is real pain in computers when 2.0 - 1.0 could produce 0.999999999999 that is not equal to1.0 :). That can be especially easy stumbled upon in javascript form validations.
I have code to calculate the percentage difference between 2 numbers - (oldNum - newNum) / oldNum * 100; - where both of the numbers are doubles. I expected to have to add some sort of checking / exception handling in case oldNum is 0. However, when I did a test run with values of 0.0 for both oldNum and newNum, execution continued as if nothing had happened and no error was thrown. Running this code with ints would definitely cause an arithmetic division-by-zero exception. Why does Java ignore it when it comes to doubles?
Java's float and double types, like pretty much any other language out there (and pretty much any hardware FP unit), implement the IEEE 754 standard for floating point math, which mandates division by zero to return a special "infinity" value. Throwing an exception would actually violate that standard.
Integer arithmetic (implemented as two's complement representation by Java and most other languages and hardware) is different and has no special infinity or NaN values, thus throwing exceptions is a useful behaviour there.
The result of division by zero is, mathematically speaking, undefined, which can be expressed with a float/double (as NaN - not a number), it isn't, however, wrong in any fundamental sense.
As an integer must hold a specific numerical value, an error must be thrown on division by zero when dealing with them.
When divided by zero ( 0 or 0.00 )
If you divide double by 0, JVM will show Infinity.
public static void main(String [] args){ double a=10.00; System.out.println(a/0); }
Console:
Infinity
If you divide int by 0, then JVM will throw Arithmetic Exception.
public static void main(String [] args){
int a=10;
System.out.println(a/0);
}
Console: Exception in thread "main" java.lang.ArithmeticException: / by zero
But if we divide int by 0.0, then JVM will show Infinity:
public static void main(String [] args){
int a=10;
System.out.println(a/0.0);
}
Console: Infinity
This is because JVM will automatically type cast int to double, so we get infinity instead of ArithmeticException.
The way a double is stored is quite different to an int. See http://firstclassthoughts.co.uk/java/traps/java_double_traps.html for a more detailed explanation on how Java handles double calculations. You should also read up on Floating Point numbers, in particular the concept of Not a Number (NaN).
If you're interested in learning more about floating point representation, I'd advise reading this document (Word format, sorry). It delves into the binary representation of numbers, which may be helpful to your understanding.
Though Java developers know about the double primitive type and Double class, while doing floating point arithmetic they don't pay enough attention to Double.INFINITY, NaN, -0.0 and other rules that govern the arithmetic calculations involving them.
The simple answer to this question is that it will not throw ArithmeticException and return Double.INFINITY. Also, note that the comparison x == Double.NaN always evaluates to false, even if x itself is a NaN.
To test if x is a NaN, one should use the method call Double.isNaN(x) to check if given number is NaN or not. This is very close to NULL in SQL.
It may helpful for you.
In Java, (Number/0) throws an ArithmeticException while (Number/0.0) = Infinity.
Why does this happen?
Because IEEE-754 floating point numbers have a representation for infinity, whereas integers don't.
In other words, every bit pattern in int represents a normal integer; floating point values are rather more complicated with +/- infinity, "not a number" (NaN) values, normalized values, subnormal values etc.
From here
The IEEE floating-point standard, supported by almost all modern processors, specifies that every floating point arithmetic operation, including division by zero, has a well-defined result. The standard supports signed zero, as well as infinity and NaN (not a number). There are two zeroes, +0 (positive zero) and −0 (negative zero) and this removes any ambiguity when dividing. In IEEE 754 arithmetic, a ÷ +0 is positive infinity when a is positive, negative infinity when a is negative, and NaN when a = ±0. The infinity signs change when dividing by −0 instead.
Integer division by zero is usually handled differently from floating point since there is no integer representation for the result. Some processors generate an exception when an attempt is made to divide an integer by zero, although others will simply continue and generate an incorrect result for the division. The result depends on how division is implemented, and can either be zero, or sometimes the largest possible integer.
Also you can check the JLS which says:
15.17.2 Division Operator
On the other hand, if the value of the divisor in an integer division is 0, then
an ArithmeticException is thrown.
The result of a floating-point division is determined by the specification of
IEEE arithmetic:
If the result is not NaN, the sign of the result is positive if both operands have
the same sign, negative if the operands have different signs.
Division of a nonzero finite value by a zero results in a signed infinity.
The sign is determined by the rule stated above.
How can we use them in our codes, and what will cause NaN(not a number)?
Positive infinity means going to infinity in the positive direction -- going into values that are larger and larger in magnitude in the positive direction.
Negative infinity means going to infinity in the negative direction -- going into values that are larger and larger in magnitude in the negative direction.
Not-a-number (NaN) is something that is undefined, such as the result of 0/0.
And the constants from the specification of the Float class:
Float.NEGATIVE_INFINITY
Float.POSITIVE_INFINITY
Float.NaN
More information can be found in the IEEE-754 page in Wikipedia.
Here's a little program to illustrate the three constants:
System.out.println(0f / 0f);
System.out.println(1f / 0f);
System.out.println(-1f / 0f);
Output:
NaN
Infinity
-Infinity
This may be a good reference if you want to learn more about floating point numbers in Java.
Positive Infinity is a positive number so large that it can't be represented normally. Negative Infinity is a negative number so large that it cannot be represented normally. NaN means "Not a Number" and results from a mathematical operation that doesn't yield a number- like dividing 0 by 0.
In Java, the Double and Float classes both have constants to represent all three cases. They are POSITIVE_INFINITY, NEGATIVE_INFINITY, and NaN.
Plus consider this:
double a = Math.pow(10, 600) - Math.pow(10, 600); //==NaN
Mathematically, everybody can see it is 0. But for the machine, it is an "Infinity" - "Infinity" (of same Rank), which is indeed NaN.
1/0 will result in positive infinity.
0/0 will result in Nan. You can use NaN as any other number, eg: NaN+NaN=NaN, NaN+2.0=NaN
-1/0 will result in negative infinity.
Infinity (in java) means that the result of an operation will be such an extremely large positive or negative number that it cannot be represented normally.
The idea is to represent special numbers which can arise naturally from operations on "normal" numbers. You could see infinity (both positive and negative) as "overflow" of the floating point representation, the idea being that in at least some conditions, having such a value returned by a function still gives meaningful result. They still have some ordering properties, for example (so they won't screw sorting operations, for example).
Nan is very particular: if x is Nan, x == x is false (that's actually one way to test for nan, at least in C, again). This can be quite confusing if you are not used to floating point peculiarities. Unless you do scientific computation, I would say that having Nan returned by an operation is a bug, at least in most cases that come to mind. Nan can come for various operations: 0/0, inf - inf, inf/inf, 0 * inf. Nan does not have any ordering property, either.
You can use them as any other number:
e.g:
float min = Float.NEGATIVE_INFINITY;
float max = Float.POSITIVE_INFINITY;
float nan = Float.NaN;
Positive Infinity is a positive number so large that it can't be
represented normally. Negative Infinity is a negative number so large
that it cannot be represented normally. NaN means "Not a Number" and
results from a mathematical operation that doesn't yield a number-
like dividing 0 by 0.
this is not a complete answer(or not clarified enough) - consider this:
double a = Math.pow(10,600) - Math.pow(10,600); //==NaN
mathematically everybody can see it is 0. but for the machine it is an "Infinity" - "Infinity"(of same order) witch is indeed NaN...