The following code sample prints 1.5.
float a = 3;
float b = 2;
a /= b;
System.out.println(a);
I don't understand what the /= operator does. What is it supposed to represent?
It's a combination division-plus-assignment operator.
a /= b;
means divide a by b and put the result in a.
There are similar operators for addition, subtraction, and multiplication: +=, -= and *=.
%= will do modulus.
>>= and <<= will do bit shifting.
It is an abbreviation for x = x / y (x /= y). What it does is it divides the variable to be asigned by the left hand side of it and stores it in the right hand side. You can always change:
x = x / y
to
x /= y
You can do this with most other operators like * / + and -. I am not sure about bitwise operators though.
a/=b; implies that divide a with b and put the result into a
A/=B means the same thing as A=(A/B)
Java (copying from C) has a whole set of operators X op = Y meaning X=X op Y, for op being any of: + - * / % & | ^
X/=Y it is same as X=X/Y.
Also you can try the same thing for these operators + - * %
As most people here have already said, x/=y is used as a shortened form of x=x\y and the same works for other operators like +=, -=, *=, %=. There's even further shortcuts for + and - where x++ and x-- represent x=x+1 and x=x-1 respectively.
One thing that hasn't been mentioned is that if this is used in some function call or conditional test the original value is used then replaced, letting you do the iterator for a while loop inside the call that uses that iterator, or write a true mod function using the remainder operator much more concisely:
public int mod(int a, int b){
return ((a%=b)>=0?a:a+b);
}
which is a much shorter way of writing:
public int mod(int a, int b){
a = a % b
if (a>=0){
return a;
}
return a+b;
}
You could say a = a / b OR (for short) say a /= b
Related
This question already has answers here:
What is the difference between += and =+?
(9 answers)
What is the purpose of the =+ operator in Java? [duplicate]
(2 answers)
Closed 9 years ago.
I've the following code:
public class Operators {
public static void main(String[] args) {
int i =+ 2;
System.out.println(i);
}
}
Upon executing I'm getting the following output: 2
So what does =+ operator actually does here?
EDIT:
As some answered, it is assigning +2 to i, consider the following code:
public class Operators {
public static void main(String[] args) {
int i =- -2;
System.out.println(i);
}
}
So in above case, output should be -2. But I'm getting 2
So I suppose, it is -(-2), which gives 2. Right?
int i =+ 2;
It is positive 2(+2) assignment to variable i. It is more miningful or understandable if your write like -- int i = +2;
One more example -
int i = 2;
i=+3;
System.out.println(i);
It prints 3.
+ Unary plus operator; indicates
positive value (numbers are
positive without this, however)
More example - http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/java/nutsandbolts/examples/UnaryDemo.java
Upon saying:
int i =+ 2;
+ acts as a unary operator.
To elaborate, it sets i to a positive value 2.
EDIT: Your update says:
int i =- -2;
produces 2. Why?
In this case, it implies that i=-(-(2)). Note that using a unary minus operator might produce unexpected results when the value is, say, Integer.MIN_VALUE.
I believe what you mean by =+ is really +=.
Your code is assigning the value of +2 (positive 2) to the integer.
For example:
int x =+ 4;
x =+ 8;
Console.WriteLine(x.ToString());
Console.ReadLine();
Will print "8", not 12. This is because you are assigning x to +4 and then +8.
If you are asking about what += does, it is a shorthand to takes the initial variable and add to it.
x += 8
is the same as
x = x + 8
By changing the previous example form =+ to += give us:
int x = 4;
x += 8;
Console.WriteLine(x.ToString());
Console.ReadLine();
Will print "12".
You are setting i equal to +2, which is what you got. What kind of output are you expecting?
Refer to the following image for unary operators.
Here is an exmaple to understand it.
public class UnaryDemo {
public static void main(String[] args) {
int x = 10;
int y = 20;
int result = +x;
System.out.println("+x = " + result);
result = -y;
System.out.println("-y = " + result);
}
}
and the output is
+x = 10
-y = -20
So think the operator as variable = +value rather than variable =+ values. yeah That space makes it more readable.
As all others are answered, I want to give the JLS reference.
Answer to your Edit
int i =- -2;
As specified in jls
Unary numeric promotion (§5.6.1) is performed on the operand.
The type of the unary minus expression is the promoted type of the operand.
At run time, the value of the unary minus expression is the arithmetic negation of the promoted value of the operand.
So,
System.out.println(i); //prints 2
For integer values, negation is the same as subtraction from zero.
Note
For floating-point values, negation is not the same as subtraction from zero, because if x is +0.0, then 0.0-x is +0.0, but -x is -0.0.
Unary minus merely inverts the sign of a floating-point number. Special cases of interest:
If the operand is NaN, the result is NaN. (Recall that NaN has no sign (§4.2.3).)
If the operand is an infinity, the result is the infinity of opposite sign.
If the operand is a zero, the result is the zero of opposite sign.
Useful links
unary operators
Unary Numeric Promotion
I'd like a way to calculate (x + y)/2 for any two integers x, y in Java. The naive way suffers from issues if x+y > Integer.MAX_VALUE, or < Integer.MIN_VALUE.
Guava IntMath uses this technique:
public static int mean(int x, int y) {
// Efficient method for computing the arithmetic mean.
// The alternative (x + y) / 2 fails for large values.
// The alternative (x + y) >>> 1 fails for negative values.
return (x & y) + ((x ^ y) >> 1);
}
... but this rounds towards negative infinity, meaning the routine doesn't agree with the naive way for values like {-1, -2} (giving -2, rather than -1).
Is there any corresponding routine which truncates towards 0?
"Just use long" is not the answer I'm looking for, since I want a method that works for long inputs too. BigInteger is also not the answer I'm looking for. I don't want a solution with any branches.
You need to add 1 to the result if the lowest bits are different (so the result is not exact and you need to round), and the sign bit in the result is set (the result is negative, so you want to change the round down into a round up).
So the following should do (untested):
public static int mean(int x, int y) {
int xor = x ^ y;
int roundedDown = (x & y) + (xor >> 1);
return roundedDown + (1 & xor & (roundedDown >>> 31));
}
Why don't you do something like (x-y)/2 + y, which reduces to x/2 - y/2 + y = x/2 + y/2? So if x+y gives you an overflow or underflow, you do it the (x-y)/2 + y way.
I want to know how to obtain the remainder by dividing an integer with another integer (both positive) using bitshift or bitwise operators only. The / operator or % operator should not be used.
For example, for obtaining the remainder when divisor is of the form 2^k the following operation yields the remainder.
m = Remainder
n = The number
d = The divisor
m = n & ( d - 1 )
However this method works only when d is of the form 2^k . I want to know a similar method for non-powers of 2. I am currently working on a problem from programming challenges and want to employ such a method to reduce program execution time
Any answer that doesn't use the operator % will be a less efficient answer, but, if you absolutely cannot use the operator, then, one solution is to use a loop to subtract d from n repeatedly:
m = n;
while (m >= d)
{
m -= d;
}
Assuming that your integers are 32-bit, then you can consider an optimized version where we delete multiples of d from n:
m = n;
for (i = 31; i >= 0; i--)
{
di = d << i;
if (di > 0 && m >= di) m -= di;
}
This example, assumes the integers are signed and watches for overflow i.e. the test for di > 0.
Is there any Java function or util class which does rounding this way: func(3/2) = 2
Math.ceil() doesn't help, which by name should have done so. I am aware of BigDecimal, but don't need it.
Math.ceil() will always round up, however you are doing integer division with 3/2. Thus, since in integer division 3/2 = 1 (not 1.5) the ceiling of 1 is 1.
What you would need to do to achieve the results you want is Math.ceil(3/2.0);
By doing the division by a double amount (2.0), you end up doing floating point division instead of integer division. Thus 3/2.0 = 1.5, and the ceil() of 1.5 is always 2.
A bit of black magic, and you can do it all with integers:
// Divide x by n rounding up
int res = (x+n-1)/n
To convert floor division to ceiling division:
(numerator + denominator-1) / denominator
To convert floor division to rounding division:
(numerator + (denominator)/2) / denominator
You can always cast first:
Math.ceil((double)3/2)
In Java, 3/2 = 1 because it uses integer division. There's no function that can "fix" this afterwards. What you have to do is to force a float divison and round up the result:
int result = (int)Math.ceil( ((float)3) / ((float)2) );
Aint this the usual case of integer division? Try Math.Ceil after casting either number to a floating point type.
Many languages "think" like this. If you're dividing an int into an int, then you should get an int (so they truncate and you get 1 as a result).
We all know this is not true, but that's how they work. You can "cheat" them, and do something like casting one of them to a double, or use a double representation: Math.ceil (3.0 / 2) or Math.ceil((double)3/2), as mentioned.
Math.ceil will help, provided you use floating point numbers. The problem is that 3/2, in integer division, is 1. By the time the value gets to whatever function, be it Math.ceil or something else, the value is simply 1. Any trailing decimal portion is gone.
if (a % b == 0)
{
return (a / b);
}
else
{
return (a / b) + 1;
}
Exploits integer division to do what you want. I don't know of a math function that does this, but why not roll your own?
below fragment works with negative integers as well:
public static int divRoundUp(int x, int n) {
if (n<=0) throw new RuntimeException("conceived wt. pos. dividers (was:"+n+")");
int ret = (x+(n-1)*(x>0?1:0))/n;
return ret;
}
If you want to just divide by 2, you can do:
n - n / 2
And in general:
(n - 1) / d + 1 == (n + d - 1) / d
This holds for non-negative integers. How to extend it to negative integers depends on what you mean with "does rounding this way". Integer division is rounded towards zero, whereas Math.ceil() rounds up and Math.floor() rounds down. For example n / 2 != (int) Math.floor(n / 2.0) for n == -5.
If you want to always round up, you can use Math.ceil() as in this answer.
If you really want to avoid using ceil and casting, here is a little method that accomplishes the same thing.
public int findCeil(int X, int Y) {
if (X % Y == 0){
return X / Y;
} else {
return X / Y + 1;
}
}
I like Randy Proctor's answer the best. Here in more detail:
If you want to do real rounding (i.e. 3/2 -> 2, but 17 / 7 -> 2) with integers > 0:
use (dividend + (divisor / 2)) / divisor instead of dividend / divisor.
If dividend can be any integer (i.e. negative allowed):
(dividend >= 0) ? ((dividend + divisor / 2) / divisor) : ((dividend - divisor / 2) / divisor).
If dividend is any integer and divisor any integer but 0:
(dividend >= 0) ? ((dividend + Math.abs(divisor) / 2) / divisor) : ((dividend - Math.abs(divisor) / 2) / divisor).
(Note that the addition and substraction can cause a wraparound that otherwise wouldn't occur, rendering the result incorrect.)
Here is a method I created to handle int division without using Math Round and casting to float. This works for positive and negative numbers. It works by adding half of the denominator to offset the rounding down
public static int div_Int(int num, int den){
if(num > 0 && den > 0 || num < 0 && den < 0 ){
return ((2*num)+ den)/(2*den);
}else{
return ((2*num)- den)/(2*den);
}
}
Have you tried Math.floor() ?
I am looking to implement the simple equation:
i,j = -Q ± √(Q2-4PR) / 2P
To do so I have the following code (note: P = 10. Q = 7. R = 10):
//Q*Q – 4PR = -351 mod 11 = -10 mod 11 = 1, √1 = 1
double test = Math.sqrt(modulo(((Q*Q) - ((4*P)*R))));
// Works, but why *-10 needed?
i = (int)(((-Q+test)/(P*2))*-10); // i = 3
j = (int)(((-Q-test)/(P*2))*-10); // j = 4
To put it simply, test takes the first part of the equation and mods it to a non-zero integer in-between 0 and 11, then i and j are written. i and j return the right number, but for some reason *-10 is needed to get them right (a number I guessed to get the correct values).
If possible, I'd like to find a better way of performing the above equation because my way of doing it seems wrong and just works. I'd like to do it as the equation suggests, rather than hack it to work.
The quadratic equation is more usually expressed in terms of a, b and c. To satisfy ax2+bx+c = 0, you get (-b +/- sqrt(b^2-4ac)) / 2a as answers.
I think your basic problem is that you're using modulo for some reason instead of taking the square root. The factor of -10 is just a fudge factor which happens to work for your test case.
You should have something like this:
public static void findRoots(double a, double b, double c)
{
if (b * b < 4 * a * c)
{
throw new IllegalArgumentException("Equation has no roots");
}
double tmp = Math.sqrt(b * b - 4 * a * c);
double firstRoot = (-b + tmp) / (2 * a);
double secondRoot = (-b - tmp) / (2 * a);
System.out.println("Roots: " + firstRoot + ", " + secondRoot);
}
EDIT: Your modulo method is currently going to recurse pretty chronically. Try this instead:
public static int modulo(int x)
{
return ((x % 11) + 11) % 11;
}
Basically the result of the first % 11 will be in the range [-10, 10] - so after adding another 11 and taking % 11 again, it'll be correct. No need to recurse.
At that point there's not much reason to have it as a separate method, so you can use:
public static void findRoots(double a, double b, double c)
{
int squareMod11 = (((b * b - 4 * a * c) % 11) + 11) % 11;
double tmp = Math.sqrt(squareMod11);
double firstRoot = (-b + tmp) / (2 * a);
double secondRoot = (-b - tmp) / (2 * a);
System.out.println("Roots: " + firstRoot + ", " + secondRoot);
}
You need to take the square root. Note that Q^2-4PR yields a negative number, and consequently you're going to have to handle complex numbers (or restrict input to avoid this scenario). Apache Math may help you here.
use Math.sqrt for the square root. Why do you cast i and j to ints? It is equation giving you roots of square function, so i and j can be any complex numbers. You shall limit the discriminant to positive-only values for real (double) roots, otherwise use complex numbers.
double test = Q*Q - 4*P*R;
if(Q < 0) throw new Exception("negative discriminant!");
else {
test = Math.sqrt(test);
double i = (-Q + test) / 2*P;
double i = (-Q - test) / 2*P;
}
Why are you doing modulo and not square root? Your code seems to be the way to get the roots of a quadratic equation ((a±sqrt(b^2-4ac))/2a), so the code should be:
double delta = Q*Q-4*P*R);
if(delta < 0.0) {
throw new Exception("no roots");
}
double d = Math.power(delta,0.5);
double r1 = (Q + d)/(2*P)
double r2 = (Q - d)/(2*P)
As pointed out by others, your use of mod isn't even wrong. Why are you making up mathematics like this?
It's well known that the naive solution to the quadratic equation can have problems if the value of b is very nearly equal to the discriminant.
A better way to do it is suggested in section 5.6 of "Numerical Recipes in C++": if we define
(source: equationsheet.com)
Then the two roots are:
and
Your code also needs to account for pathological cases (e.g., a = 0).
Let's substitute your values into these formulas and see what we get. If a = 10, b = 7, and c = 10, then :
(source: equationsheet.com)
Then the two roots are:
(source: equationsheet.com)
and
(source: equationsheet.com)
I think I have the signs right.
If your calculation is giving you trouble, it's likely due to the fact that you have complex roots that your method can't take into account properly. You'll need a complex number class.