When I call Math.ceil(5.2) the return is the double 6.0. My natural inclination was to think that Math.ceil(double a) would return a long. From the documentation:
ceil(double a)
Returns the smallest (closest to negative infinity) double value
that is not less than the argument and is equal to a mathematical
integer.
But why return a double rather than a long when the result is an integer? I think understanding the reason behind it might help me understand Java a bit better. It also might help me figure out if I'll get myself into trouble by casting to a long, e.g. is
long b = (long)Math.ceil(a);
always what I think it should be? I fear there could be some boundary cases that are problematic.
The range of double is greater than that of long. For example:
double x = Long.MAX_VALUE;
x = x * 1000;
x = Math.ceil(x);
What would you expect the last line to do if Math.ceil returned long?
Note that at very large values (positive or negative) the numbers end up being distributed very sparsely - so the next integer greater than integer x won't be x + 1 if you see what I mean.
A double can be larger than Long.MAX_VALUE. If you call Math.ceil() on such a value you would expect to return the same value. However if it returned a long, the value would be incorrect.
Related
long mynum = Long.parseLong("7660142319573120");
long ans = (long)Math.sqrt(mynum) // output = 87522239
long ans_ans = ans * ans;
In this case, I am getting ans_ans > mynum where it should be <=mynum. Why such behavior? I tried this with node js as well. There also result is same.
Math.sqrt operates on doubles, not longs, so mynum gets converted to a double first. This is a 64-bits floating point number, which has "15–17 decimal digits of precision" (Wikipedia).
Your input number has 16 digits, so you may be losing precision on the input already. You may also be losing precision on the output.
If you really need an integer square root of long numbers, or generally numbers that are too big for accurate representation as a double, look into integer square root algorithms.
You can also use LongMath.sqrt() from the Guava library.
You are calling Math.sqrt with a long.
As the JavaDoc points out, it returns a "correctly rounded value".
Since your square-root is not an non-comma-value (87522238,999999994), your result is rounded up to your output 87522239.
After that, the square of the value is intuitively larger than mynum, since you multiply larger numbers than the root!
double ans = (double)Math.sqrt(15);
System.out.println("Double : " + ans);
double ans_ans = ans * ans;
System.out.println("Double : " + ans_ans);
long ans1 = (long)Math.sqrt(15);
System.out.println("Long : " + ans1);
long ans_ans1 = ans1 * ans1;
System.out.println("Long : " + ans_ans1);
Results :
Double : 3.872983346207417
Double : 15.000000000000002
Long : 3
Long : 9
I hope this makes it clear.
The answer is: rounding.
The result of (Long)Math.sqrt(7660142319573120) is 87522239, but the mathematical result is 87522238,999999994287166259537761....
if you multiply the ans value, which is rounded up in order to be stored as a whole number, you will get bigger number than multiplying the exact result.
You do not need the long type, all numbers are representable in double, and Math.sqrt first converts to double then computes the square root via FPU instruction (on a standard PC).
This situation occurs for numbers b=a^2-1 where a is an integer in the range
67108865 <= a <= 94906265
The square root of b has a series expansion starting with
a-1/(2*a)-1/(8*a^2)+...
If the relative error 1/(2*a^2) falls below the machine epsilon, the closest representable double number is a.
On the other hand for this trick to work one needs that a*a-1.0 is exactly representable in double, which gives the conditions
1/(2*a^2) <mu=2^(-53) < 1/(a^2)
or
2^52 < a^2 < 2^53
2^26+1=67108865 <= a <= floor(sqrt(2)*2^26)=94906265
I have the following code in my project:
int percent = 2;
int count = 10;
int percentagefill = (percent/10)*count;
System.out.println(percentagefill);
Basically what is happening is that, I'm setting two variables, percent and count. I then calculate the percentage fill. For some strange reason the percentage fill is resulting in a 0, when in this case it should be 2. Any ideas why? Thanks in advance.
intdivided by int will still result in int. In this case:
(percent/10)*count
= (2/10)*10
= (0) * 10 <-- 0.2 is rounded down to 0
= 0
You can read this question for reference. Also, here's the Java spec where is says that integer division is rounded towards 0. As for the fix, as long as floating point precision does not become an issue, just use double as PaulP.R.O said.
You could divide by 10.0, or change int percent to double percent in order to force a conversion to double. Otherwise, you are getting integer division, which truncates off the decimal part.
Here is a relevant question: "Java Integer Division, How do you produce a double?"
if you really need the result to be an int, you could do the multiply before the divide to avoid the integer division giving you zero.
int percentagefill = (percent*count)/10;
Change this line:
int percentagefill = (percent/10)*count;
To:
double percentagefill = (percent/10.0)*count;
This will use floating point arithmetic (because of the 10.0 instead of 10), and store the result in a double (which has precision past the decimal point unlike an int).
As others have mentioned, you're losing precision with integer division
The solution depends on your needs: if your result needs to be an integer anyway, multiply first:
int percentagefill = (percent*count)/10;
Could be "good enough" for you (you'll get the correct answer rounded down).
If you need to be able to get fractional answers, you need to convert things to floating point types:
double percentagefill = (percent/10.0)*count;
// ^ the .0 makes this a double,
// forcing the division to be a
// floating-point operation.
It's easy to fix:
int percent = 2;
int count = 10;
double percentagefill = (percent/10.0)*count;
System.out.println(percentagefill);
Dave Newton, your answer should have been an answer. :)
The integer 2 / the integer 10 = 0.
The integer 0 * the integer 10 = 0.
You will need a float or double data type. While working with information, always be weary of chances for the interpreter to make data type assumptions and "casts". println takes an intefer and casts to a string for display is one example.
Most of my work is in php and when working with values, 0, NULL, ERROR can all be different things and can yield unexpected results. Sometimes you may need to explicitly cast a variable to a different data type to get the intended results.
This is so due to the fact that you are using the integer data type when you should be using a floating-point data type such as double. This code should result in 2.0:
double percent = 2;
double count = 10;
double percentagefill = (percent/10)*count;
System.out.println(percentagefill);
In Java, I want to convert a double to an integer, I know if you do this:
double x = 1.5;
int y = (int)x;
you get y=1. If you do this:
int y = (int)Math.round(x);
You'll likely get 2. However, I am wondering: since double representations of integers sometimes look like 1.9999999998 or something, is there a possibility that casting a double created via Math.round() will still result in a truncated down number, rather than the rounded number we are looking for (i.e.: 1 instead of 2 in the code as represented) ?
(and yes, I do mean it as such: Is there any value for x, where y will show a result that is a truncated rather than a rounded representation of x?)
If so: Is there a better way to make a double into a rounded int without running the risk of truncation?
Figured something: Math.round(x) returns a long, not a double. Hence: it is impossible for Math.round() to return a number looking like 3.9999998. Therefore, int(Math.round()) will never need to truncate anything and will always work.
is there a possibility that casting a double created via Math.round() will still result in a truncated down number
No, round() will always round your double to the correct value, and then, it will be cast to an long which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.
Here are the docs from Math.round(double):
Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:
(long)Math.floor(a + 0.5d)
For the datatype Double to int, you can use the following:
Double double = 5.00;
int integer = double.intValue();
Double perValue = 96.57;
int roundVal= (int) Math.round(perValue);
Solved my purpose.
This code:
System.out.println(Math.abs(Integer.MIN_VALUE));
Returns -2147483648
Should it not return the absolute value as 2147483648 ?
Integer.MIN_VALUE is -2147483648, but the highest value a 32 bit integer can contain is +2147483647. Attempting to represent +2147483648 in a 32 bit int will effectively "roll over" to -2147483648. This is because, when using signed integers, the two's complement binary representations of +2147483648 and -2147483648 are identical. This is not a problem, however, as +2147483648 is considered out of range.
For a little more reading on this matter, you might want to check out the Wikipedia article on Two's complement.
The behaviour you point out is indeed, counter-intuitive. However, this behaviour is the one specified by the javadoc for Math.abs(int):
If the argument is not negative, the argument is returned.
If the argument is negative, the negation of the argument is returned.
That is, Math.abs(int) should behave like the following Java code:
public static int abs(int x){
if (x >= 0) {
return x;
}
return -x;
}
That is, in the negative case, -x.
According to the JLS section 15.15.4, the -x is equal to (~x)+1, where ~ is the bitwise complement operator.
To check whether this sounds right, let's take -1 as example.
The integer value -1 is can be noted as 0xFFFFFFFF in hexadecimal in Java (check this out with a println or any other method). Taking -(-1) thus gives:
-(-1) = (~(0xFFFFFFFF)) + 1 = 0x00000000 + 1 = 0x00000001 = 1
So, it works.
Let us try now with Integer.MIN_VALUE . Knowing that the lowest integer can be represented by 0x80000000, that is, the first bit set to 1 and the 31 remaining bits set to 0, we have:
-(Integer.MIN_VALUE) = (~(0x80000000)) + 1 = 0x7FFFFFFF + 1
= 0x80000000 = Integer.MIN_VALUE
And this is why Math.abs(Integer.MIN_VALUE) returns Integer.MIN_VALUE. Also note that 0x7FFFFFFF is Integer.MAX_VALUE.
That said, how can we avoid problems due to this counter-intuitive return value in the future?
We could, as pointed out by #Bombe, cast our ints to long before. We, however, must either
cast them back into ints, which does not work because
Integer.MIN_VALUE == (int) Math.abs((long)Integer.MIN_VALUE).
Or continue with longs somehow hoping that we'll never call Math.abs(long) with a value equal to Long.MIN_VALUE, since we also have Math.abs(Long.MIN_VALUE) == Long.MIN_VALUE.
We can use BigIntegers everywhere, because BigInteger.abs() does indeed always return a positive value. This is a good alternative, though a bit slower than manipulating raw integer types.
We can write our own wrapper for Math.abs(int), like this:
/**
* Fail-fast wrapper for {#link Math#abs(int)}
* #param x
* #return the absolute value of x
* #throws ArithmeticException when a negative value would have been returned by {#link Math#abs(int)}
*/
public static int abs(int x) throws ArithmeticException {
if (x == Integer.MIN_VALUE) {
// fail instead of returning Integer.MAX_VALUE
// to prevent the occurrence of incorrect results in later computations
throw new ArithmeticException("Math.abs(Integer.MIN_VALUE)");
}
return Math.abs(x);
}
Use a integer bitwise AND to clear the high bit, ensuring that the result is non-negative: int positive = value & Integer.MAX_VALUE (essentially overflowing from Integer.MAX_VALUE to 0 instead of Integer.MIN_VALUE)
As a final note, this problem seems to be known for some time. See for example this entry about the corresponding findbugs rule.
Here is what Java doc says for Math.abs() in javadoc:
Note that if the argument is equal to
the value of Integer.MIN_VALUE, the
most negative representable int value,
the result is that same value, which
is negative.
To see the result that you are expecting, cast Integer.MIN_VALUE to long:
System.out.println(Math.abs((long) Integer.MIN_VALUE));
There is a fix to this in Java 15 will be a method to int and long. They will be present on the classes
java.lang.Math and java.lang.StrictMath
The methods.
public static int absExact(int a)
public static long absExact(long a)
If you pass
Integer.MIN_VALUE
OR
Long.MIN_VALUE
A Exception is thrown.
https://bugs.openjdk.java.net/browse/JDK-8241805
I would like to see if either Long.MIN_VALUE or Integer.MIN_VALUE is passed a positive value would be return and not a exception but.
2147483648 cannot be stored in an integer in java, its binary representation is the same as -2147483648.
But (int) 2147483648L == -2147483648 There is one negative number which has no positive equivalent so there is not positive value for it. You will see the same behaviour with Long.MAX_VALUE.
Math.abs doesn't work all the time with big numbers I use this little code logic that I learnt when I was 7 years old!
if(Num < 0){
Num = -(Num);
}
I have a double value d and would like a way to nudge it very slightly larger (or smaller) to get a new value that will be as close as possible to the original but still strictly greater than (or less than) the original.
It doesn't have to be close down to the last bit—it's more important that whatever change I make is guaranteed to produce a different value and not round back to the original.
(This question has been asked and answered for C, C++)
The reason I need this, is that I'm mapping from Double to (something), and I may have multiple items with the save double 'value', but they all need to go individually into the map.
My current code (which does the job) looks like this:
private void putUniqueScoreIntoMap(TreeMap map, Double score,
A entry) {
int exponent = 15;
while (map.containsKey(score)) {
Double newScore = score;
while (newScore.equals(score) && exponent != 0) {
newScore = score + (1.0d / (10 * exponent));
exponent--;
}
if (exponent == 0) {
throw new IllegalArgumentException("Failed to find unique new double value");
}
score = newScore;
}
map.put(score, entry);
}
In Java 1.6 and later, the Math.nextAfter(double, double) method is the cleanest way to get the next double value after a given double value.
The second parameter is the direction that you want. Alternatively you can use Math.nextUp(double) (Java 1.6 and later) to get the next larger number and since Java 1.8 you can also use Math.nextDown(double) to get the next smaller number. These two methods are equivalent to using nextAfter with Positive or Negative infinity as the direction double.
Specifically, Math.nextAfter(score, Double.MAX_VALUE) will give you the answer in this case.
Use Double.doubleToRawLongBits and Double.longBitsToDouble:
double d = // your existing value;
long bits = Double.doubleToLongBits(d);
bits++;
d = Double.longBitsToDouble(bits);
The way IEEE-754 works, that will give you exactly the next viable double, i.e. the smallest amount greater than the existing value.
(Eventually it'll hit NaN and probably stay there, but it should work for sensible values.)
Have you considered using a data structure which would allow multiple values stored under the same key (e.g. a binary tree) instead of trying to hack the key value?
What about using Double.MIN_VALUE?
d += Double.MIN_VALUE
(or -= if you want to take away)
Use Double.MIN_VALUE.
The javadoc for it:
A constant holding the smallest positive nonzero value of type double, 2-1074. It is equal to the hexadecimal floating-point literal 0x0.0000000000001P-1022 and also equal to Double.longBitsToDouble(0x1L).