what is NaN? and how is been created? [duplicate] - java

This question already has answers here:
In Java, what does NaN mean?
(11 answers)
Closed 5 years ago.
I have a double[] and it has a value which is NaN. When I add up the array's elements, the NaN makes the result NaN too.
How did it happen? How can I prevent this NaN from being added to the rest of my array?

NaN stands for Not-a-Number. It can arise in a variety of ways, for example as a result of 0./0., sqrt(-1), or as the result of a calculation involving other NaNs.
The easiest way to check whether v is a NaN is by using Double.isNaN(v):
public static double sum(double arr[]) {
double sum = 0.0;
for (double val : arr) {
if (!Double.isNaN(val)) {
sum += val;
}
}
return sum;
}
edit: #Stephen C makes a good point in the comments: before deciding to ignore that NaN, it would be prudent to understand where it came from. It could be that it is the result of a bug elsewhere in your code, and by blindly ignoring the NaN you could simply be masking the bug instead of fixing it.

NaN stands for "Not a Number", so "Not A Number" + 10 = "Not a Number"
You might want to consider debuggin your app to find what's in the double array :)

how can i prevent that this NaN not bein added to the rest of my double[]
This way:
double[] array = something;
double sum = 0;
for (int i = 0; i < array.length; i++) {
if (!Double.isNaN(array[i])) {
sum += array[i];
}
}

RTFM:
Javadoc for NaN
public static final double NaN
A constant holding a Not-a-Number (NaN) value of type double. It is equivalent to the value returned by Double.longBitsToDouble(0x7ff8000000000000L).
And relevant section of the JVM spec says any operation involving a NaN is also a NaN (a bit like a null in SQL)

You can't just ignore the NaN, it's an indicator of a problem with you're program. You need to find out what is causing the NaN and fix that.

NaN - Not a Number
btw try :
double[] array = new double[10];
String result = StringUtils.join(array);
System.out.println(result+ " BATMAN !");

Java isn't my strong suit, but in other languages this comes from assigning a value from a string. Try this:
parseDouble
public static double parseDouble(String s)
throws NumberFormatException
Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.
Parameters:
s - the string to be parsed.
Returns:
the double value represented by the string argument.
Throws:
NumberFormatException - if the string does not contain a parsable double.
Since:
1.2
See Also:
valueOf(String)
Taken from here.

Related

Is Double.POSITIVE_INFINITY a true representation of infinity? [duplicate]

This question already has answers here:
What are the INFINITY constants in Java, really?
(3 answers)
Closed 5 years ago.
I was wondering if Java's 'Double.POSITIVE_INFINITY' is a true representation of infinity and, if not, will 'i' from this code:
public class Infinity {
private static int i;
public static void main(String[] args) {
double inf = Double.POSITIVE_INFINITY;
for (i = 0; i < inf; i++) {
}
System.out.println(i);
}
}
Ever be printed?
i < inf will always be true; i.e. i will never reach Double.POSITIVE_INFINITY.
That's because int will overflow to a negative once it reaches 2,147,483,647.
Note that even if i was a double type, you still wouldn't attain POSITIVE_INFINITY: that's because after the 53rd power of 2, certain single increments are a no-op.
Even if you change your code to
double inf = Double.POSITIVE_INFINITY;
for (double i = 0.0; i < inf; i++) {
}
System.out.println(i);
The loop will never end, since i can never become larger than Double.MAX_VALUE, and Double.MAX_VALUE is still smaller than Double.POSITIVE_INFINITY.
You can prove it by running this snippet:
if (Double.MAX_VALUE > Double.POSITIVE_INFINITY) {
System.out.println ("max is larger than infinity");
} else {
System.out.println ("nope");
}
which will print "nope", since Double.POSITIVE_INFINITY is larger than any possible double value. BTW, the compiler marks the System.out.println ("max is larger than infinity"); statement as dead code.
I guess this means you could say 'Double.POSITIVE_INFINITY' is a true representation of infinity.
BTW, the value of POSITIVE_INFINITY is
public static final double POSITIVE_INFINITY = 1.0 / 0.0;
Therefore, since 1.0/0.0 is actually positive infinity, you can say it's a true representation of infinity.
int has 4 bytes. It ranges from -2,147,483,648 to 2,147,483,647.
( see here for example).
Which is way smaller than Double.POSITIVE_INFINITY.
( see here ).
So your loop simply runs over and over and over ...
And a more "philosophical" bonus answer: why do you need to ask other people?! You learn programming by making experiments. Yourself.
In other words: that inner curious to "try and find out" is what helps you becoming a programmer. Asking for clarification is fine; but asking for explanations without you trying anything is the wrong approach. Doing so slows down your learning!

Why does type double PI = 22/7 returns 3, but double PI = 22.0/7 or 22/7.0 returns correct result 3.14..? [duplicate]

This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 8 years ago.
I tried of finding answer by googling as well as debugging variable behavior, but unfortunately I dint find any proper answer. Its a question related to Java for instance.
Question :
Why 'double' type variable behaves like 'int' type in below condition :
double PI = 22/7 which returns 3
but, double PI = 22.0/7 or 22/7.0 returns 3.14xxxxxxx ?
Help appreciated...Thanks.
Because that's how Java (and some other programming languages) have been implemented.
Since both are integers, the expected result will be an integer as well:
int/int = int
In the other hand, when one operator is double, the result will also be double
double/int = double
int/double = double
Because in java arithmetic operations output gives the result in terms of highest data type among all involved variables or constants(Applied only on primitive data types).
For example if in any arithmetic operation like below:
Scenario 1=> var1 is int, var 2 is float, var3 is double: You will get result in double
Scenario 2=> var1 is short, var2 is long and var3 is float: you will get result in float
Scenario 3=> var1 is int, var2 is long, var3 is double: you will get result in double
Note: float family data type(float & double) always dominate to int family data types even both have same size, like in case of long and float output will be in float.
Because by default in java numerals are integer data type, so, when you are doing numeric operation with integers, the result also will be integer. When you assign that integer to a double variable, it is promoted to a double, but its value is kept. So you end up with a double with the exact same value as the result integer -- in this case, 3.0.
In your first case, both are integers, so the result also an integer, and you have assigned to double. But the conversion(integer to double) happened before assignment to double.
In the second or third case, one in double, so the operation done on double, So the result also a double value.
Or 'Pi= 22D / 7D' does it too. Here 22 and 7 are declared as 'double', not 'int'.
public static void main(String[] args) {
double d = 22 / 7; // same as double d = (int)22 / (int) 7
System.out.println(d); // so prints 3.0
double dd = 22.0/7; // same as double dd = (double)22 / (int) 7
System.out.println(dd);//prints 3.14xxxx
}

round towards zero in java

How to round in java towards zero?
So -1.9 becomes -1.0 and -0.2 becomes 0.0, 3.4 becomes 3.0 and so on.
Is Math.round() capable of doing this changing some parameters?
I do not believe that the standard library has such a function.
The problem is that you are asking for very different behavior (mathematically speaking) depending on whether the number is larger or smaller than 0 (i.e. rounding up for negative values, rounding down for positive values)
The following method could be used:
public double myRound(double val) {
if (val < 0) {
return Math.ceil(val);
}
return Math.floor(val);
}
cast to long like this:
float x= 1.9;
long y = (long)x;
This rounds both positive and negative numbers towards zero.
Use RoundingMode.DOWN, it leads towards zero.
Example :
BigDecimal value = new BigDecimal("1.4");
value = value.setScale(0, RoundingMode.DOWN);
System.out.println(value.doubleValue());
BigDecimal value1 = new BigDecimal("-1.4");
value1 = value1.setScale(0, RoundingMode.DOWN);
System.out.println(value1.doubleValue());
Just casting to int will do that for you?
Edit: If you want to retain a double this should work simply enough:
if (val < 0)
return -Math.floor(-val);
else
return Math.floor(val);
And just for the people who want branch free code and feel a bit more clever:
long tmp = Double.doubleToLongBits(val);
tmp >>>= 63;
return Math.floor(val) + tmp;
y=sign(x)*floor(abs(x))
or
y=sign(x)*round(abs(x)-0.5)
It should be easy to implement in Java.
Seems like you want to always round-down? You can use Math.floor instead
public static double floor(double a)
Returns the largest (closest to positive infinity) double value that
is not greater than the argument and is equal to a mathematical
integer. Special cases:
BigDecimal offers many rounding options.
You also can try this:
public static void main(String[] args) {
Double myDouble = -3.2;
System.out.println(myDouble.intValue()); //Prints -3
}

Why does the division of two integers return 0.0 in Java? [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
int totalOptCount = 500;
int totalRespCount=1500;
float percentage =(float)(totalOptCount/totalRespCount);
Why does this always return value 0.0? Also I want to format this into 00.00 format and convert into string?
Because the conversion to float happens after the division has been done. You need:
float percentage = ((float) totalOptCount) / totalRespCount;
You should be able to format using something like:
String str = String.format("%2.02f", percentage);
If you are using int values, using a double may be a better choice and have less rounding error. float can represent int values without error up to ~16 million. double can accurately represent all int values.
double percentage =(double) totalOptCount / totalRespCount;
Percentages are usually multiplied by 100, meaning you can drop the cast.
double percentage = 100.0 * totalOptCount / totalRespCount;
(totalOptCount/totalRespCount)
here both dividend and divisor are of type int which means they will allow only integer values and the answer of such equation will always be an integer literal.
if I break this it will be something like below
(double)(500/1500)
According to the actual calculation, 500/1500 will give you 0.33333 but compiler will convert this into integer literal because both operands are of type int
(double)(0)
Compiler gets an instruction to cast this 0 value to double so you got 0.0 as result
0.0
and then you can change the result to any format as suggeted by #Zach Janicki.
keep in mind if both the operands are of same type than result will be of same type too.
Integer division (which includes long, short, byte, char, int) in Java always returns an int (or long, if one of the parameters is long), rounding towards zero. Your conversion occurs after this calculation.
(The formatting question is already answered by the other answers - alternatively you could also have a look at java.text.NumberFormat, specially java.text.DecimalFormat.)
String.format("%2.02f", (float)totalOptCount/totalRespCount);
to format a double and print out as a percentage, you can use use
System.out.println(new DecimalFormat("##.##").format(yourDouble) + "%"));

How to represent NaN in array of numbers?

The question says it all. I have an array of doubles and am doing something with them.
double expectedOutput[] = { 6.38792, 12.91079, 14.33333, 13.44517,
12.34539, 12.05397, 8.34061, 2.07900, -2.01999, -5.47802,
-8.21610, -9.26719, -11.02378 };
Ideally, i would test to see if
6.38792 == 6.38792 and end up with a 'pass'
Under certain conditions, i end up with the situation like
6.38792 != NaN
Knowing that this is a valid case sometimes, how can i represent NaN in my code?
I either need to include NaNs into my array of expected elements or somehow figure out that result is Not A Number
I am using Java
In Java, you can get NaN by using
Double.NaN
So you can just put this into your array.
If your question is how to check if something is NaN, you can call
Double.isNan(/* ... value ... */);
You'll have to test for it explicitly, since NaN != NaN, you can't just include it in your array. You have to use Double.isNaN(x).
double d = 0.0/0.0;
if(Double.isNan(d)){
// Double d is not a number.
}
Alternatively:
double d = Double.Nan;
if(Double.isNan(d)){
// Double d is not a number.
}
Since in many languages NaN is not equal to itself (and in Java also), you should handle it as a specific case. Use Float.NaN or Double.NaN to reference NaN. Use Float.isNaN or Double.isNaN to check if a specific value is NaN.
This is a case where Double objects actually are more useful than primitive doubles.
// auto-boxes them all to Double objects
Collection<Double> expectedOutput =
Arrays.asList(6.38792, 12.91079, 14.33333, 13.44517, 12.34539,
12.05397, 8.34061, 2.07900, -2.01999, -5.47802,
-8.21610, -9.26719, -11.02378, Double.NaN );
// maybe fill into HashSet for more efficient lookup?
// later:
double d = Double.NaN;
if(expectedOutput.contains(d)) {
System.out.println("found");
}
The reason is that Double.equals in fact implements the reflexivity condition of the equals contract, meaning that Double.valueOf(Double.NaN).equals(Double.valueOf(Double.NaN)) gives true, contrary to Double.NaN != Double.NaN.

Categories

Resources