how to reduce days of periods in unix time in java [duplicate] - java

why is 24 * 60 * 60 * 1000 * 1000 divided by 24 * 60 * 60 * 1000 not equal to 1000 in Java?

Because the multiplication overflows 32 bit integers. In 64 bits it's okay:
public class Test
{
public static void main(String[] args)
{
int intProduct = 24 * 60 * 60 * 1000 * 1000;
long longProduct = 24L * 60 * 60 * 1000 * 1000;
System.out.println(intProduct); // Prints 500654080
System.out.println(longProduct); // Prints 86400000000
}
}
Obviously after the multiplication has overflowed, the division isn't going to "undo" that overflow.

You need to start with 24L * 60 * ... because the int overflows.
Your question BTW is a copy/paste of Puzzle 3: Long Division from Java Puzzlers ;)

If you want to perform that calculation, then you must either re-order the operations (to avoid overflow) or use a larger datatype. The real problem is that arithmetic on fixed-size integers in Java is not associative; it's a pain, but there's the trade-off.

Related

Android studio warns about integer multiplication implicitly cast to long. How to fix this?

private static boolean isOverDate(long targetDate, int threshold) {
return new Date().getTime() - targetDate >= threshold * 24 * 60 * 60 * 1000;
}
I am using above function and Android Studio warns me about:
threshold * 24 * 60 * 60 * 1000: integer multiplication implicitly cast to long
How to fix this? And why it warns?
OK, so this is a bit complicated to unpick.
On the LHS (left hand side) of the >= expression we have:
new Date().getTime() - targetDate
The type of that expression is long because targetDate is declared as long.
On the RHS we have:
threshold * 24 * 60 * 60 * 1000
That is an int because all of the operands are ints.
However that expression is likely to overflow. The value of 24 * 60 * 60 * 1000 is a "rather large", and when you multiply it by threshold, the resulting value is liable to be too big to represent as an int. If it does overflow, then the result will be truncated, and the >= test will give the wrong result.
So ... the compiler is suggesting that you should do the RHS calculation using long arithmetic. The simple way would be to declare threshold as a long. But you could also cast it to a long as in:
((long) threshold) * 24 * 60 * 60 * 1000
Since max_int is 2 147 483 648.
If your threshold is more than 25 (25 * 24 * 60 * 60 * 1000 = 2.160.000.000), it will higher than int can hold. So you will need to cast to long or the result may be incorrect.
Reference: https://stackoverflow.com/a/42671759/4316327
If an integer multiplication overflows, then the result is the
low-order bits of the mathematical product as represented in some
sufficiently large two's-complement format. As a result, if overflow
occurs, then the sign of the result may not be the same as the sign of
the mathematical product of the two operand values.
Solution:
long timeToCheck = threshold * 24 * 60 * 60 * 1000L;
return new Date().getTime() - targetDate >= timeToCheck;
or single line (different here is L after last number, it will understand that you will change type to long)
return new Date().getTime() - targetDate >= threshold * 24 * 60 * 60 * 1000L;
or casting
return new Date().getTime() - targetDate >= (long) threshold * 24 * 60 * 60 * 1000;

How to calculate output of an Overflow value

I have been asked a question in Interview which was related to Integer overflow. The question was simple but I could not find a an easy solution to count the result of overflowed value.
For Example, Following program should print 1000 as output but it prints 5 due the Integer overflow.
public class IntegerOvewflow {
/**
* Java does not have target typing, a language feature wherein the type of the
* variable in which a result is to be stored influences the type of the
* computation.
*
* #param args
*/
public static void main(String[] args) {
final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000;
final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);
}
}
But, here can we use any specific formula or equation to calculate the output of overflowed value. Here the number is really big and not easy to judge the output quickly by human mind.
Specify that they are long with L, because if not you're doing int multiplication which results in an int which touch the overflow and then store into a long
public static void main(String[] args) {
final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000L;
final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000L;
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY); // 1000
}
Check out : https://ideone.com/5vHjnH
This is the classic Problem from the very good book , Java Puzzlers Link to Book
Puzzle 3: Long Division
This puzzle is called Long Division because it concerns a program that divides
two long values. The dividend represents the number of microseconds in a day;
the divisor, the number of milliseconds in a day. What does the program print?
public class LongDivision {
public static void main(String[] args) {
final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000;
final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);
}
}
Solution 3: Long Division
This puzzle seems reasonably straightforward. The number of milliseconds per
day and the number of microseconds per day are constants.
For clarity, they are expressed as products.
The number of microseconds per day is (24 hours/day · 60
minutes/hour · 60 seconds/minute · 1,000 milliseconds/second · 1,000 microseconds/millisecond).
The number of milliseconds per day differs only in that it is
missing the final factor of 1,000. When you divide the number of microseconds
per day by the number of milliseconds per day, all the factors in the divisor cancel
out, and you are left with 1,000, which is the number of microseconds per millisecond. Both the divisor and the dividend are of type long, which is easily large
enough to hold either product without overflow.
It seems, then, that the program
must print 1000. Unfortunately, it prints 5. What exactly is going on here?
The problem is that the computation of the constant MICROS_PER_DAY does
overflow. Although the result of the computation fits in a long with room to spare,
it doesn’t fit in an int. The computation is performed entirely in int arithmetic,
and only after the computation completes is the result promoted to a long. By
then, it’s too late: The computation has already overflowed, returning a value that
is too low by a factor of 200. The promotion from int to long is a widening primitive conversion [JLS 5.1.2], which preserves the (incorrect) numerical value. This
value is then divided by MILLIS_PER_DAY, which was computed correctly because
it does fit in an int. The result of this division is 5.
So why is the computation performed in int arithmetic? Because all the factors that are multiplied together are int values. When you multiply two int values, you get another int value. Java does not have target typing, a language
feature wherein the type of the variable in which a result is to be stored influences
the type of the computation.
It’s easy to fix the program by using a long literal in place of an int as the
first factor in each product. This forces all subsequent computations in the expression to be done with long arithmetic. Although it is necessary to do this only in
the expression for MICROS_PER_DAY, it is good form to do it in both products. Similarly, it isn’t always necessary to use a long as the first value in a product, but it is good form to do so. Beginning both computations with long values makes it clear that they won’t overflow.
This program prints 1000 as expected:
public class LongDivision {
public static void main(String[] args) {
final long MICROS_PER_DAY = 24L * 60 * 60 * 1000 * 1000;
final long MILLIS_PER_DAY = 24L * 60 * 60 * 1000;
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);
}
}
The lesson is simple: When working with large numbers, watch out for
overflow—it’s a silent killer. Just because a variable is large enough to hold a
result doesn’t mean that the computation leading to the result is of the correct
type. When in doubt, perform the entire computation using long arithmetic.
The lesson for language designers is that it may be worth reducing the likelihood of silent overflow. This could be done by providing support for arithmetic
that does not overflow silently. Programs could throw an exception instead of
overflowing, as does Ada, or they could switch to a larger internal representation
automatically as required to avoid overflow, as does Lisp. Both of these
approaches may have performance penalties associated with them. Another way
to reduce the likelihood of silent overflow is to support target typing, but this adds
significant complexity to the type system [Modula-3 1.4.8].
You can use BigInteger class for exactly these purposes.
Oracle documentation: here
There is a good quick article in this link

how to get number of micro seconds in a day

I want to get the number of micro seconds in a day
so I tried as per below
long microDay = 24 * 60 * 60 * 1000 * 1000;
for which I am expecting value as 86400000000 but when I print it
System.out.println(microDay);
The value is 500654080
After spending 3 hours and breaking my head to know the reason,final I found that java think 24,60 and 1000 as int values and int*int =int but the maximum value of int is 2147483647 so it cant store 86400000000 and hence it the output is 500654080 (but I am not sure)
In the second case I wanted to calculate miliseconds in a day and the formula goes like this
long miliDay = 24 * 60 * 60 * 1000;
System.out.println(miliDay );
output 86400000
now when I did
System.out.println(microDay/ miliDay);
output 5
but when I tried this in a calculator 500654080/86400000= 5.794607407407407
why there is different in result?
You're performing 32-bit integer arithmetic, as every operand in 24 * 60 * 60 * 1000 * 1000 is an int... but the result is bigger than Integer.MAX_VALUE, so it's overflowing (just as you suspected). (This is actually happening at compile-time in this case, because it's a compile-time constant, but the effect is the same as if it happened at execution time.)
Effectively, each operation is truncated to 32 bits. As it happens, only the final multiplication by 1000 takes the result over 231 - 86400000 is fine.
86400000000 in binary is:
1010000011101110101110110000000000000
^
\- Bit 33
So after overflow, we just chop any leading bits until we've got 32:
00011101110101110110000000000000
And that value is 500654080.
Just use long instead, e.g.
long microDay = 24L * 60L * 60L * 1000L * 1000L;
(You definitely don't need all those constants to be of type long, but being consistent means it's obvious that all the operations will be performed using 64-bit arithmetic, with no need to consider associativity etc.)
A better approach, however, would be to use TimeUnit:
long microDay = TimeUnit.DAYS.toMicroseconds(1);
As for the division part, you're performing integer division - so the result is the integer part, rounded towards 0. If you want floating point arithmetic, you need to cast one of the operands to float or double... although if you start off with the right values, of course, you should get an exact integer anyway (1000).
For the first part, put a "L" at the end of one (or more) of the constants and Java will then use long arithmetic. e.g.
long microDay = 24L * 60 * 60 * 1000 * 1000;
Addendum: Why did you get 500654080?
86400000000 decimal = 141DD76000 hex.
But, the integer only holds 32 bits, which is 8 "digits". So you lose the leading 14 and retain 1DD76000 hex.
Converting that to decimal gives 500654080.
As for the division, when you divide ints by ints (or longs by longs) Java returns the result as an int or long, so it has to truncate (or round, but Java chose to truncate) the result to 5 instead of 5.7946... Force it to do floating point arithmetic by casting one of the values to a double, e.g.
System.out.println((double)microDay/ miliDay);
When you are performing a division between 2 integers, the results are an integer. The results of the arithmetic operation will be rounded down to the nearest integer.
int i = 5 / 2; // 2.5 is rounded down to 2
if you want the output to include the decimal precision, you will need to use a different primitive data type and explicitly specify your operands to be doubles.
double j = 5 / 2; //2.0 as 5 / 2 yields and integer 2 which will be casted to a double
double j = 5 / 2.0; //2.5 explicit usage of a double will tell the compiler to return the results in double
The nuclear operations inside
long microDay = 24 * 60 * 60 * 1000 * 1000;
are all Integers specific. Max value of Integer object is 2147483647. Which exceeds the original output which is long.
Simply specifying long to variable doesn't mean all operations using [ * ] will be done using long instances. All operations done in assignment became sort of truncated.
Solution is to explicitly specify that all nuclear operations should happen over long instance and not int instances.
long microDay = 24L * 60L * 60L * 1000L * 1000L;

Multiplication of two int's gets negative

I'm currently coding a little download manager and I get a funny output when I try to calculate the download-progress in percent. This is what i use to calculate it:
int progress = (byte_counter * 100) / size;
System.out.println("("+byte_counter+" * 100) = "+(byte_counter * 100)
+" / "+size+" = "+progress);
byte-counter is an int (it counts the total bytes read from the InputStream) and size is the length of the downloaded file in bytes.
This works great with small downloads. But when i get to bigger files (40MB) it starts making funny things. The Output for the calculation looks like this:
[...]
(21473280 * 100) = 2147328000 / 47659008 = 45
(21474720 * 100) = 2147472000 / 47659008 = 45
(21476160 * 100) = -2147351296 / 47659008 = -45
(21477600 * 100) = -2147207296 / 47659008 = -45
[...]
I don't know why, but the calculation gets negative. Since an normal Integer should be fine with numbers till 231-1, this shouldn't be the problems root. But what am I missing?
See http://en.wikipedia.org/wiki/Arithmetic_overflow
To fix in java, try using a long instead.
int progress = (int) ((byte_counter * 100L) / size);
or reverse order of operations
int progress = (int) (((float) byte_counter) / size) * 100);
21476160 * 100 = 2 147 616 000 is greater than 2 147 483 647, the max int.
You're overflowing.
Use long for your calculations.
2^31-1 = 2147483647 < 21476160 * 100 = 2147616000
You should use a long -- 2147760000 in binary is 10000000 00000100 00110111 10000000 and since the most significant bit is 1 it is interpreted as a negative number.

why is 24 * 60 * 60 * 1000 * 1000 divided by 24 * 60 * 60 * 1000 not equal to 1000 in Java?

why is 24 * 60 * 60 * 1000 * 1000 divided by 24 * 60 * 60 * 1000 not equal to 1000 in Java?
Because the multiplication overflows 32 bit integers. In 64 bits it's okay:
public class Test
{
public static void main(String[] args)
{
int intProduct = 24 * 60 * 60 * 1000 * 1000;
long longProduct = 24L * 60 * 60 * 1000 * 1000;
System.out.println(intProduct); // Prints 500654080
System.out.println(longProduct); // Prints 86400000000
}
}
Obviously after the multiplication has overflowed, the division isn't going to "undo" that overflow.
You need to start with 24L * 60 * ... because the int overflows.
Your question BTW is a copy/paste of Puzzle 3: Long Division from Java Puzzlers ;)
If you want to perform that calculation, then you must either re-order the operations (to avoid overflow) or use a larger datatype. The real problem is that arithmetic on fixed-size integers in Java is not associative; it's a pain, but there's the trade-off.

Categories