How do I check if a zero is positive or negative? - java

Is it possible to check if a float is a positive zero (0.0) or a negative zero (-0.0)?
I've converted the float to a String and checked if the first char is a '-', but are there any other ways?

Yes, divide by it. 1 / +0.0f is +Infinity, but 1 / -0.0f is -Infinity. It's easy to find out which one it is with a simple comparison, so you get:
if (1 / x > 0)
// +0 here
else
// -0 here
(this assumes that x can only be one of the two zeroes)

You can use Float.floatToIntBits to convert it to an int and look at the bit pattern:
float f = -0.0f;
if (Float.floatToIntBits(f) == 0x80000000) {
System.out.println("Negative zero");
}

Definitly not the best aproach. Checkout the function
Float.floatToRawIntBits(f);
Doku:
/**
* Returns a representation of the specified floating-point value
* according to the IEEE 754 floating-point "single format" bit
* layout, preserving Not-a-Number (NaN) values.
*
* <p>Bit 31 (the bit that is selected by the mask
* {#code 0x80000000}) represents the sign of the floating-point
* number.
...
public static native int floatToRawIntBits(float value);

Double.equals distinguishes ±0.0 in Java. (There's also Float.equals.)
I'm a bit surprised no-one has mentioned these, as they seem to me clearer than any method given so far!

The approach used by Math.min is similar to what Jesper proposes but a little clearer:
private static int negativeZeroFloatBits = Float.floatToRawIntBits(-0.0f);
float f = -0.0f;
boolean isNegativeZero = (Float.floatToRawIntBits(f) == negativeZeroFloatBits);

When a float is negative (including -0.0 and -inf), it uses the same sign bit as a negative int. This means you can compare the integer representation to 0, eliminating the need to know or compute the integer representation of -0.0:
if(f == 0.0) {
if(Float.floatToIntBits(f) < 0) {
//negative zero
} else {
//positive zero
}
}
That has an extra branch over the accepted answer, but I think it's more readable without a hex constant.
If your goal is just to treat -0 as a negative number, you could leave out the outer if statement:
if(Float.floatToIntBits(f) < 0) {
//any negative float, including -0.0 and -inf
} else {
//any non-negative float, including +0.0, +inf, and NaN
}

For negative:
new Double(-0.0).equals(new Double(value));
For positive:
new Double(0.0).equals(new Double(value));

Just use Double.compare (d1,d2).
double d1 = -0.0; // or d1 = 0.0
if ( Double.compare (d1, 0.0) < 0 )
System.out.println("negative zero");
else
System.out.println("positive zero");

Related

java - what is the fastest way(method) to test if double is an int and how to decide?

how can i tell which method is better to use for my situation or faster?.
for example:-
public boolean isSquareNumber(){
double nd = Math.sqrt(num); // num is a class member variable.
if(nd == Math.floor(nd))
{
return true;
} else {
return false;
}
}
and this method
public boolean isSquareNumber(){
double nd = Math.sqrt(num);
if(nd == (int)Math.sqrt(nd))
{
return true;
} else {
return false;
}
}
Math.floor() and Math.sqrt().
both were exactly the same for this situation but how do i decide which is faster?.
Thank you for your time <3.
The fastest way to test if a double value is an integer will be this:
double d = ...
if (d == ((long) d)) {
// It is an integer
}
Note that is (theoretically) possible for sqrt(someValue) to produce an double value that is indistinguishable from an integer value, even though the true square root of someValue is not an integer. As the javadoc states:
Otherwise, the result is the double value closest to the true mathematical square root of the argument value.
So you could get a case where the "closest" double value corresponds to an integer, even though the actual square root is irrational.
The other point of contention is whether Math.floor is actually correct.
On the one hand, the narrowing cast and Math.floor are different:
narrowing uses IEE 754 "rounding towards zero" mode
Math.floor() returns "the largest (closest to positive infinity) floating-point value that less than or equal to the argument and is equal to a mathematical integer". In other words, it rounds towards negative infinity.
On the other hand, if we are testing a double value that is known to be non-negative1, then rounding towards zero and towards negative infinity are the same thing.
1 - Is this the case for Math.sqrt()? Strictly no, since sqrt(-0.0) is defined to return -0.0 ... per the javadoc. However, -0.0 should be treated as +0.0 for the purposes of rounding.

Identifying the type of data

How to identify decimal portion value that exists with a float data type?
If the decimal part results as zero, exempting the decimal portion shall be a good practice. How this can be achieved when dealing with float values making it easeful?
Your variables num1 and num2 are both floats not integers as mentioned in your question, I guess that what you want to achieve is to find a way to know if a given float has decimals or not and for this you can proceed as next:
float f = 46.0f;
if (f % 1.0 == 0.0){
System.out.printf("float without decimal %.0f%n", f);
} else {
System.out.printf("float with decimals %.2f%n", f);
}
Output:
float without decimal 46
inputValue.getClass().getName()
example: value: type = java.lang.String
inputValue.getClass().getSimpleName();
example: value: String
Ended up with the below solution.
if (Value - (int) Value) != 0)
//Contains the decimal portion
else
//Decimal portion doesn't exist
Helps in identifying the type of value stored and avoid unnecessary usage of decimal portion if an int value.

Difference between Math.min() and if condition

What way is the best to get minimum number and which improved the performance or both are same as performance wise?
One way to get the min distance between two number :
double minDistance = Double.MAX_VALUE;
double distance = coordinate1.distnaceTo(coordinate2);
if(distnace < minDistance ) {
minDistance = distance;
}
Another way to get the min distance between two number :
double minDistance = Double.MAX_VALUE;
double minDistance = Math.min(coordinate1.distnaceTo(coordinate2), minDistance);
If you are dealing with positive numbers, not equal to NaN, -0.0 or 0.0, then there shouldn't be much difference.
The following from the Math.min source code in Java 8 highlights the following differences:
If either value is NaN, then the result is NaN. Unlike the numerical comparison operators, this method considers negative zero to be
strictly smaller than positive zero. If one argument is positive zero
and the other is negative zero, the result is negative zero.
So Math.min may be slightly less efficient since it checks for NaN and -0.0 vs 0.0, but it is arguably more readable - you need to consider firstly whether the special cases are applicable or not, and then readability vs (ever so slight) performance difference after that.
Personally I would use Math.min, but that's my own opinion.
Java Math#min(double, double) does the following:
Returns the smaller of two double values. That is, the result is the value closer to negative infinity.
If the arguments have the same value, the result is that same value.
If either value is NaN, then the result is NaN.
If one argument is positive zero and the other is negative zero, the result is negative zero.
Take a look at the source:
public static double min(double a, double b) {
if (a != a) return a; // a is NaN
if ((a == 0.0d) && (b == 0.0d) && (Double.doubleToLongBits(b) == negativeZeroDoubleBits)) {
return b;
}
return (a <= b) ? a : b;
}
And here is your implementation:
if(distnace < minDistance ) {
....
}
So, yes your code is a little bit faster than Math.min() as it checks some additional condition, NaN, zero or negativity whereas your if-else doesn't care any of those.

Perfect Java code to determine a Double is a Perfect Square or not?

I want to determine whether a number (in double) is a perfect square or not. I have used the below code but it fails for many inputs.
private static boolean isSquare(double i) {
double s = Math.sqrt(i);
return ((s*s) == i);
}
When s results in scientific form, the code fails. For example when s is 2.719601835756618E9
Your code makes no attempt to test whether the square root of the number is an integer. Any nonnegative real number is the square of some other real number; your code's result depends entirely on floating-point rounding behavior.
Test whether the square root is an integer:
if (Double.isInfinite(i)) {
return false;
}
sqrt = Math.sqrt(i);
return sqrt == Math.floor(sqrt) && sqrt*sqrt == i;
The sqrt*sqrt == i check should catch some cases where a number exceptionally close to a square has a square root whose closest double approximation is an integer. I have not tested this and make no warranties as to its correctness; if you want your software to be robust, don't just copy the code out of the answer.
UPDATE: Found a failing edge case. If an integer double has a greatest odd factor long enough that the square is not representable, feeding the closest double approximation of the square to this code will result in a false positive. The best fix I can think of at the moment is examing the significand of the square root directly to determine how many bits of precision it would take to represent the square. Who knows what else I've missed, though?
static boolean checkPerfectSquare(double x)
{
// finding the square root of given number
double sq = Math.sqrt(x);
/* Math.floor() returns closest integer value, for
* example Math.floor of 984.1 is 984, so if the value
* of sq is non integer than the below expression would
* be non-zero.
*/
return ((sq - Math.floor(sq)) == 0);
}
I know that the question is old, but I would post my solution anyway:
return Math.sqrt(i) % 1d == 0;
Simply check if the sqrt has decimals.

Bitwise operation OR on (double) in Java not possible, possible in JavaScript

Here is outputs from Google Chrome Javascript Console.
Here is outputs from DrJava Java Console.
My Javascript code is
(baseCPUCyclesPerIteration - CPUCyclesTotalRoundoff) | 0
Seems to compile fine in Java if both variables are integers but apparently they are doubles in javascript. Even though
typeof baseCPUCyclesPerIteration reveals "number"
The results make it pretty obvious it's a double datatype. I don't understand why bitwise OR 0 works on a double in Javascript but doesn't work on Java double's.
Seems the purpose of the | 0 is just to trim of the decimal points in double datatype. I'm guessing in Java the equivalent will be (int) or (long) cast is this correct? or the bitwise | 0 does more then just trim of the decimal point in javascript?
Edit:
ya | 0 doesn't just trim in javascript just ran this. 8899811111.111113453456754645 | 0 got back 309876519.
(Although I passed the double limit lol still tries to compute it in javascript, I'm guessing this is where the overflows happen).
In javascript, all bitwise operators will cast decimal numbers to 32 bit integers. It acts like floor for positive numbers and ceil for negative numbers. Things like |0 or ~~ are often used as tricks to cast numbers to integer in JavaScript.
To explain the overflow you're seeing, we can look at the specifications for how Javascript converts numbers to int32: http://es5.github.io/#x9.5
The abstract operation ToInt32 converts its argument to one of 2^32 integer values in the range −2^31 through 2^31−1, inclusive. This abstract operation functions as follows:
Let number be the result of calling ToNumber on the input argument.
If number is NaN, +0, −0, +∞, or −∞, return +0.
Let posInt be sign(number) * floor(abs(number)).
Let int32bit be posInt modulo 2^32; that is, a finite integer value k of Number type with positive sign and less than 2^32 in magnitude such that the mathematical difference of posInt and k is mathematically an integer multiple of 2^32.
If int32bit is greater than or equal to 2^31, return int32bit − 2^32, otherwise return int32bit.
So, to reproduce this behavior, you would have to reproduce this logic.
Edit: Here's how Mozilla's Rhino engine does it in Java: (as per the github link supplied by user3435580)
public static int toInt32(double d) {
int id = (int)d;
if (id == d) {
// This covers -0.0 as well
return id;
}
if (d != d
|| d == Double.POSITIVE_INFINITY
|| d == Double.NEGATIVE_INFINITY)
{
return 0;
}
d = (d >= 0) ? Math.floor(d) : Math.ceil(d);
double two32 = 4294967296.0;
d = Math.IEEEremainder(d, two32);
// (double)(long)d == d should hold here
long l = (long)d;
// returning (int)d does not work as d can be outside int range
// but the result must always be 32 lower bits of l
return (int)l;
}

Categories

Resources