Is there a form of the // operator that is used in python that I can use in java, or some sort of workaround?
10 // 3 = 3
In python 3 // act as a floor division by default.
In python 2.2 and later 2.X version we can import it from the __future__
>>> from __future__ import division
>>> 10/3
3.3333333333333335
>>> 10//3
3
In Java:
When dividing floating-point variables or values, the fractional part of the answer is represented in the floating-point variable.
float f = 10.0f / 6.0f; // result is 1.6666
double d = 10.0 / 9.0; // result is 1.1111
But for floor in java:
(int)Math.floor(10/3);
One thing to notice is:
in python 3:
6 // -132 = -1
in java:
6 / -132 = 0
public static int python_like_divisor(int x, int y) {
final remainder = x % y;
if(remainder != 0) {
return (x - remainder) / y;
}
return x / y;
}
Some basic math knowledge is good ;)
With float-point (float, double etc.) values this method will not work properly.
Java's integer division will act in the same way as the // operator in Python. This means that something like this:
(int) 9/4 == 2 is True
The cast here is even unnecessary because both 9 and 4 are integers. If one was a float or a double this cast would be necessary as java would no longer execute this statement as integer division. To be more explicit you could do this
(int)Math.floor(9 / 4);
which divides the numbers first and then floors the results to the nearest integer.
You can use
java.lang.Math#floorDiv(int, int)
Related
I have this simple code and I need to understand why the right side of the equation has been casted to Integer before getting the result in type double.
The answer here is 1.0 so I don't understand why it's not 1.5.
int x = 2;
double y = 1 + 1/x;
System.out.println(y);
simply update your code as following since you are dealing with doubles.
int x = 2;
double y = 1 + 1.0/x;
System.out.println(y);
Notice: double y = 1 + 1/x;
Modify: double y = 1 + 1.0/x;
You'll get 1.5
here x is an int and 1 is also an int so calculation is done in int and so you are getting the answer as 1.0. To get as 1.5 you have to typecast 1 to double as 1.0. Then you will get as 1.5.
I think what you meant was: why the value of 'x' on the right-hand side has not been 'promoted' to a double?
First, change the second line to :
double y = 1 + (double) 1 / x;
//or
double y = 1 + 1.0 / x;
Details:
Simply for most computers to perform arithmetic operations operands must be of identical data types.
The cast operator (double) performs explicit conversion of its operand to double, then the variable ' x ' will be implicitly converted to a double which is called promotion.
also in the second line 1.0 is already a floating-point constant so you can guess that this is the same as before, that is a promotion to the variable 'x' will occur.
What you have done in your code is called Integer Division meaning that the fractional part of the division will be lost (truncated). Note that the fractional part is lost before it is assigned to the variable y.
You may have some intuition now on why we didn't write the code like that:
double y = 1.0 + 1 / x;
clearly, (1 / x) is still integer division ...hope that helps!
Like user markspace noted in a comment, the integer division happens because / has a higher order of precedence than =, which means that the division takes place first in the statement.
double y = 1 + (1/2); // Both 1 and 2 are integers at the time of operation.
// The above equation is the same as
double y = 1 + 0; // 1/2 equals 0 because integer division just keeps the integer value
// and gets rid of the value's decimal part.
Similar to what the other answers have shown, you can do something like one of the following:
double y = 1 + 1.0/x;
// Or
double y = 1 + 1/(double)x;
Just for simplicity, when I use integer literals when assigning double values, I just make all the integers have the .0 part. For example, instead of 1, I would always put 1.0. That way, you will never accidentally get unexpected results because of unwanted integer division.
Check out this page in the Java doc for the order of precedence for operators in Java.
Now I'm try to convert some js code into java , there is a problem:
In js
46022*65535 = 3016051770
and
(46022*65535)|7867 = -1278910789
In java
46022*65535 = -1278915526 this is overflow
46022L*65535L = 3016051770L this is the same result to js
(46022*65535)|7867 = -1278910789 this one and the one below is the problem
(46022L*65535L)|7867L = 3016056507L
So , why the | operator will make two positive number to be nagtive number?
What's the different between java and js when dealing with the int and long to do this operation?
And then , how to write java code compatible with js in this situation ?
Attention:I know the range of int and long , my problem is |.
More problems :
According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators
& is also 32bit operation, then:
In js
2996101485 & 65535 = 57709
In java
2996101485 is overflow to int so I use double to store it and cast it into int when I need to do AND.
double a = 2996101485l;
double b = 65535;
int c = (int) a & (int) b; Now c = 65535
But if I use long to cast :
long c = (long) a & (long) b; Now c = 57709
So , just simply cast double into int will cause problems. And I want to know why?
I got the problem , 2996101485 can be present in 32bit in js and in java it should be long. So I write functions to convert those operations , for example, & should use this java function to run give same result in js:
private double doOR(double x, double y) {
if (x > Integer.MAX_VALUE && x <= 1l << 32) {
if (y > Integer.MAX_VALUE && y <= 1l << 32) {
return (long) x | (long) y;
} else {
return (long) x | (int) y;
}
} else {
return (int) x | (int) y;
}
}
The problem is that while numbers in JavaScript have roughly 53-bit precision (they appear to be based on floating point doubles), the bitwise OR operates on only 32 bits.
Bitwise operators treat their operands as a sequence of 32 bits (zeroes and ones), rather than as decimal, hexadecimal, or octal numbers.
This means that when working with arithmetic, long will get you the JavaScript-like arithmetic (with numbers such as yours), since Java ints will overflow; but when working with bitwise operations, int will get you the JavaScript-like results, since then both platforms are operating on 32-bit numbers.
You should use long instead.
System.out.println(46022L*65535L); // = 3016051770
Java has ints and longs.
System.out.println(Integer.MAX_VALUE); // = 2147483647
System.out.println(Long.MAX_VALUE); // = 9,223,372,036,854,775,807
As for the language difference, I can only attribute it to different precisions between the languages. If you see this question, you'll see the largest number in JS is 9,007,199,254,740,992. That's a guess, it might be for another reason.
This question already has answers here:
How to round up the result of integer division?
(18 answers)
How to round up integer division and have int result in Java? [duplicate]
(9 answers)
Closed 4 years ago.
I know I can use Math.java functions to get the floor, ceil or round value for a double or float, but my question is -- Is it possible to always get the higher integer value if a decimal point comes in my value
For example
int chunkSize = 91 / 8 ;
which will be equal to 11.375
If I apply floor, ceil or round to this number it will return 11 I want 12.
Simply If I have 11.xxx I need to get 12 , if I have 50.xxx I want 51
Sorry The chunkSize should be int
How can I achieve this?
Math.ceil() will do the work.
But, your assumption that 91 / 8 is 11.375 is wrong.
In java, integer division returns the integer value of the division (11 in your case).
In order to get the float value, you need to cast (or add .0) to one of the arguments:
float chunkSize = 91 / 8.0 ;
Math.ceil(chunkSize); // will return 12!
ceil is supposed to do just that. I quote:
Returns the smallest (closest to negative infinity) double value that
is greater than or equal to the argument and is equal to a
mathematical integer.
EDIT: (thanks to Peter Lawrey): taking another look at your code you have another problem. You store the result of integer division in a float variable: float chunkSize = 91 / 8 ; java looks at the arguments of the division and as they are both integers it performs integer division thus the result is again an integer (the result of the division rounded down). Now even if you assign this to the float chunkSize it will still be an integer(missing the double part) and ceil, round and floor will all return the same value. To avoid that add a .0 to 91: float chunkSize = 91.0 / 8;. This makes one of the arguments double precision and thus double division will be performed, returning a double result.
If you want to do integer division rounding up you can do
x / y rounded up, assuming x and y are positive
long div = (x + y - 1) / y;
In your case
(91 + 8 - 1) / 8 = 98 / 8 = 12
This works because you want to round up (add one) for every value except an exact multiple (which is why you add y - 1)
Firstly, when you write float chunkSize = 91 / 8 ; it will print 11.0 instead of 11.375
because both 91 and 8 are int type values. For the result to be decimal value, either dividend or divisor
or both have to be decimal value type. So, float chunkSize = 91.0 / 8; will result 11.375 and
now you can apply Math.ceil() to get the upper value. Math.ceil(chunkSize); will result in 12.0
I'm a self-taught beginner in java and having trouble understanding ints and doubles when used in the same equation
For example,
int x;
double x;
i = 5;
x = i / 2 + 1.0; // (answer 3.0)
z = (int) 1.0 + i / 2.0; // (answer 3.5)
What is with the rounding?
The problem is that this operation:
i / 2
... is performing an integer division. That's why 5 / 2 gives as result 2, not 2.5. This is normal behavior in Java, to perform a floating-point division you must make sure that at least one of the operands is a floating-point literal:
5 / 2.0
Now the above will return 2.5, as expected. Alternatively, you can cast either one of the operands:
((double) i) / 2
A division involving two ints will yield an int (thus, 5 / 2 = 2). If you use a double in one of the operands, it will yield a double (thus 5 / 2.0 = 2.5). The rest is operation precedence.
i / 2 = int 2 because both operands are integers and so integer division operation is used (yielding integer result)
i / 2.0 = double 2.5 because i is first coerced to double (type of the other operand) and double division is used
This is a case between integer and decimal division.
When two integers are divided, integer division is performed, that is, where the numbers are divided and the decimal component truncated.
When any number of the two numbers in question is a decimal (double/float) every other number gets treated as a decimal such that given the expression 5 / 2.0. The result will be 2.5 returned in whatever type of object 2.0 was (double by default).
Given a mixed equation such as 5 / 2 + 1.0, operator precedence defines how the expression should be evaluated. Since division has a higher precedence than addition, 5 / 2 gets evaluated as a integer division, returning 2 as an integer.
This is then added to 1.0 where the 2 gets promoted to a double before evaluation, returning the number 3.0 as a double as the final result.
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
Is there any way to calculate (for example) 50% of 120?
I tried:
int k = (int)(120 / 100)*50;
But it doesn't work.
int k = (int)(120 / 100)*50;
The above does not work because you are performing an
integer division expression (120 / 100) which result is
integer 1, and then multiplying that result to 50, giving
the final result of 50.
If you want to calculate 50% of 120, use:
int k = (int)(120*(50.0f/100.0f));
more generally:
int k = (int)(value*(percentage/100.0f));
int k = (int)(120*50.0/100.0);
Never use floating point primitive types if you want exact numbers and consistent results, instead use BigDecimal.
The problem with your code is that result of (120/100) is 1, since 120/100=1.2 in reality, but as per java, int/int is always an int.
To solve your question for now, cast either value to a float or double and cast result back to int.
I suggest using BigDecimal, rather than float or double. Division by 100 is always exact in BigDecimal, but can cause rounding error in float or double.
That means that, for example, using BigDecimal 50% of x plus 30% of x plus 20% of x will always sum to exactly x.
it is simple as 2 * 2 = 4 :)
int k = (int)(50 * 120) / 100;
Division must be float, not int
(120f * 50 / 100f)
You don't need floating point in this case you can write
int i = 120 * 50 / 100;
or
int i = 120 / 2;