Why I am getting -0.0 when 0.0 multiplied by -1???
I have taken 0.0 as float
sign=-1;
float output=0.0;
JOptionPane.showmessagedialog(null,0.0*sign);
the output shown in -0.0 instead of 0
This is an answer taken from http://www.javawebtips.com/154041/
"-0.0" Is produced when a floating-point operation results in a negative floating-point number so close to 0 that cannot be represented normally.
-2.0 / Float.POSITIVE_INFINITY -> -0.0
"-0.0" Is numerically identical to "0.0". However, some operations involving "-0.0" are different than the same operation with "0.0".
(-0.0) == 0.0 -> true
2.0 / (0.0) - Infinity
2.0 / (-0.0) ->-Infinity
Floating point values have both positive and negative zero. It may seem quirky, but there's a good reason for it (given the representational limits of floating point numbers).
You might consider casting your result to an int if you would really like the answer to just be 0.
The zeros in Java floating point do not just represent the real number zero. They are used to represent every number whose absolute magnitude is too small to be represented as a non-zero number, every underflow result.
Similarly, the infinities represent not just the result of division by zero, but every result whose absolute magnitude is too big to be represented as a finite number, every overflow result.
Making zero signed permits distinction between positive underflow results and negative underflow results, including, as already stated in another answer, getting the correct infinity on division of a non-zero number by an underflow result.
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
alert(Math.cos(Math.PI/2));
Why the result is not exact zero? Is this inaccurancy, or some implementation error?
Math.PI/2 is an approximation of the real value of pi/2. Taking the exact cosine of this approximated value won't yield zero. The value you get is an approximation of this exact value up to the precision of the underlying floating point datatype.
Using some arbitrary precision library, you can evaluate the difference between pi/2 in double precision and the exact value to
0.0000000000000000612323399573676588613032966137500529104874722961...
Since the slope of the cosine close to its zeros is 1, you would expect the cosine of the approximation of pi/2 to be approximately equal to this difference, and indeed it is.
Floating-point numbers are normally approximations. Since floating-point numbers are represented in memory as binary numbers multiplied by an exponent only numbers that are sums of powers of 2 can usually be represented.
Fractions such as 1/3 can't be written as a binary number and as such have no accurate floating-point representation. Even some numbers that can be written accurately in decimal, such as 0.1, can't be represented accurately in binary and so will not be represented correctly in floating point.
PI is an irrational number and can't be represented as floating-point, so there will be rounding errors. Do not compare floating-point numbers for equality without including a tolerance parameter. This link has a good explanation of the basics.
Comparing calculated floating point numbers for equality is almost always a bad idea, since (as others have stated) they are approximations, and errors appear.
Instead of checking for a==b, check for equality to within a threshold that makes sense for your application, as with Math.abs(a-b) < .00001. This is good practice in any programming language that represents numbers as floating point values.
If you're storing integers in floating point variables and just adding, subtracting, and multiplying, they'll stay integers (at least until they go out of bounds). But dividing, using trig functions, etc., will introduce errors that must be allowed for.
-m#
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.
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...