What does "/=" mean in Java? - java

I was checking some code online when i found the following statement
number /= 10;
I know that / mean divison and = is the assignment operator but i don't understand what it does in this case.

It is equivalent of -
number = number / 10;
It is a composite operator - consist of division and assignment. You may found something like this -
+=
-=
%= etc.
All of these above works similarly.

It means that whatever the value number contains will be divided by 10 and the result will be stored back into number.
It is exactly equivalent to
number = number / 10
Most of the major operators have it:
number *= 10
number += 10
number -= 10
number %= 10
number >>= 10
number <<= 10

It means
number =number/10;
Number divided by 10
you can also do
number operator=number
where operator can be +,/,*

This is the shorter notation for number = number / 10;
The same exists for the other operators as well:
x += y; => x = x + y;
x -= y; => x = x - y;
x *= y; => x = x * y;
x %= y; => x = x % y;

Related

Integer is printed out a different value from what it actually is? [duplicate]

This question already has answers here:
How to make the division of 2 ints produce a float instead of another int?
(9 answers)
Closed 8 years ago.
So I have this code:
int x = 435;
int y = x / 2 * 5;
If I calculate y by hand, I get a result of 1087.5. But when I print the integer y out, I get the result 1085. Why is this? Shouldn't it round to either 1088 or 1087?
It's because of integer arithmetic:
int/int = int
So, 435/2 will be
435/2 = 217
And
217*5 = 1085
What can you do? Cast the values as you need:
int y = (int)((float)x / 2 * 5);
or if you want a real result, declare the variable y as float:
float y = (float)x / 2 * 5;
this saves in result of each part as an int
so
435 / 2 == 217
217 * 5 == 1085
int value of x/2=217 and 217 * 5 == 1085 is the reason
you are dividing int value x so result will be int value (int/int=int)
x/2=217
Then
217*5=1085
Try this:
int x = 435;
double y = ((double) x / 2) * 5;
y cannot be int (or else you will lose precision). Moreover, x / 2 will yield you an integer value, hence you need to cast it to double or float
Java is using integer math, this
int x = 435;
int y = x / 2 * 5;
is equivalent to
int x = 435;
int y = x / 2; // <-- 217
y *= 5; // <-- 1085
If you wanted to round the other way try,
int x = 435;
int y = (int) Math.round(((double) x / 2) * 5); // <-- 1088
the answer is correct as -:
435/2 = 217.5 since declared as int it is rounded off to 217
217*5 = 1085
which is the required answer.
When you divide 435 by 2.
It stores 217 not 217.5 and hence after multiplying 217*5= 1085
You are trying to store a float value into INT and hence getting the truncated value.
Also,without brackets, the compiler will start to execute from LHS to RHS one by one according to priority of operator.
Your code
int x = 435;
int y = x / 2 * 5;
is actually performing the following operation.
Assigning x = 435;
Dividing first y = x / 2; // This stores y= 217
And then it multiplies y=y*5; // Finally y= 1085
Using int will truncate 217.5 into 217 and hence you are getting that answer.
Use double or float for storing the kind of answer you want
int x = 435;
double y = y=(x/2)*5
This will get you the required answer.

Increment X Mod N in One Line

I have several small programs that require infinitely looping over the integer set Z sub n. I often write the code in this manor:
int x = 0;
int n = 13; //or some other prime
while(1) {
//do stuff dependent on x
++x;
x %= n;
}
I write code mostly in C/C++ & Java so I was wondering:
Is there a way to increment x mod n in one line rather then two in either language?
Have you considered:
x = (x + 1 == n ? 0: x + 1);
The chances are the x + 1 will optimise to one instruction and at least you are guaranteed to never use division (which a bad optimiser might use when % is involved).
x = (x + 1) % n;
Not terribly surprising.
Another alternative is this
x = ++x % n; // Java
if (++x == n) x = 0;
Using x = (x + 1 == n ? 0 : x + 1); requires two additions: one for the comparison and another when the value of x is set to x + 1.

Is there any math utility method to calculate the following expression?

Is there any math utility method to calculate the following expression? Basically, I need to find the largest integer less than or equal to x which can be divided by N evenly.
x - x % N; // N is an integer.
For positive integers: (x / N) * N.
(If it needs to be strictly less than x vs <= x then use ((x-1)/N) * N, for x > 0.)
if x is a positive integer and N a power of 2 you can do x & -N
EDIT: its -n not 2-n , thanks to Peter Lawrey for pointing that out
If x is a positive integer then you can use
int result = x - x % N;
or
int result = (x/N)*N;
If x is a positive double then you can use
int result = N * (int)(x/N);

How to re-implement sin() method in Java ? (to have results close to Math.sin() )

I know Math.sin() can work but I need to implement it myself using factorial(int) I have a factorial method already below are my sin method but I can't get the same result as Math.sin():
public static double factorial(double n) {
if (n <= 1) // base case
return 1;
else
return n * factorial(n - 1);
}
public static double sin(int n) {
double sum = 0.0;
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) {
sum += Math.pow(1, i) / factorial(2 * i + 1);
} else {
sum += Math.pow(-1, i) / factorial(2 * i + 1);
}
}
return sum;
}
You should use the Taylor series. A great tutorial here
I can see that you've tried but your sin method is incorrect
public static sin(int n) {
// angle to radians
double rad = n*1./180.*Math.PI;
// the first element of the taylor series
double sum = rad;
// add them up until a certain precision (eg. 10)
for (int i = 1; i <= PRECISION; i++) {
if (i % 2 == 0)
sum += Math.pow(rad, 2*i+1) / factorial(2 * i + 1);
else
sum -= Math.pow(rad, 2*i+1) / factorial(2 * i + 1);
}
return sum;
}
A working example of calculating the sin function. Sorry I've jotted it down in C++, but hope you get the picture. It's not that different :)
Your formula is wrong and you are getting a rough result of sin(1) and all you're doing by changing n is changing the accuracy of this calculation. You should look the formula up in Wikipedia and there you'll see that your n is in the wrong place and shouldn't be used as the limit of the for loop but rather in the numerator of the fraction, in the Math.pow(...) method. Check out Taylor Series
It looks like you are trying to use the taylor series expansion for sin, but have not included the term for x. Therefore, your method will always attempt to approximate sin(1) regardless of argument.
The method parameter only controls accuracy. In a good implementation, a reasonable value for that parameter is auto-detected, preventing the caller from passing to low a value, which can result in highly inaccurate results for large x. Moreover, to assist fast convergence (and prevent unnecessary loss of significance) of the series, implementations usually use that sin(x + k * 2 * PI) = sin(x) to first move x into the range [-PI, PI].
Also, your method is not very efficient, due to the repeated evaluations of factorials. (To evaluate factorial(5) you compute factorial(3), which you have already computed in the previous iteration of the for-loop).
Finally, note that your factorial implementation accepts an argument of type double, but is only correct for integers, and your sin method should probably receive the angle as double.
Sin (x) can be represented as Taylor series:
Sin (x) = (x/1!) – (x3/3!) + (x5/5!) - (x7/7!) + …
So you can write your code like this:
public static double getSine(double x) {
double result = 0;
for (int i = 0, j = 1, k = 1; i < 100; i++, j = j + 2, k = k * -1) {
result = result + ((Math.pow(x, j) / factorial (j)) * k);
}
return result;
}
Here we have run our loop only 100 times. If you want to run more than that you need to change your base equation (otherwise infinity value will occur).
I have learned a very good trick from the book “How to solve it by computer” by R.G.Dromey. He explain it like this way:
(x3/3! ) = (x X x X x)/(3 X 2 X 1) = (x2/(3 X 2)) X (x1/1!) i = 3
(x5/5! ) = (x X x X x X x X x)/(5 X 4 X 3 X 2 X 1) = (x2/(5 X 4)) X (x3/3!) i = 5
(x7/7! ) = (x X x X x X x X x X x X x)/(7 X 6 X 5 X 4 X 3 X 2 X 1) = (x2/(7 X 6)) X (x5/5!) i = 7
So the terms (x2/(3 X 2)) , (x2/(5 X 4)), (x2/(7 X 6)) can be expressed as x2/(i X (i - 1)) for i = 3,5,7,…
Therefore to generate consecutive terms of the sine series we can write:
current ith term = (x2 / ( i X (i - 1)) ) X (previous term)
The code is following:
public static double getSine(double x) {
double result = 0;
double term = x;
result = x;
for (int i = 3, j = -1; i < 100000000; i = i + 2, j = j * -1) {
term = x * x * term / (i * (i - 1));
result = result + term * j;
}
return result;
}
Note that j variable used to alternate the sign of the term .

How to round integer in java

I want to round the number 1732 to the nearest ten, hundred and thousand. I tried with Math round functions, but it was written only for float and double. How to do this for Integer? Is there any function in java?
What rounding mechanism do you want to use? Here's a primitive approach, for positive numbers:
int roundedNumber = (number + 500) / 1000 * 1000;
This will bring something like 1499 to 1000 and 1500 to 2000.
If you could have negative numbers:
int offset = (number >= 0) ? 500 : -500;
int roundedNumber = (number + offset) / 1000 * 1000;
(int)(Math.round( 1732 / 10.0) * 10)
Math.round(double) takes the double and then rounds up as an nearest integer. So, 1732 will become 173.2 (input parameter) on processing by Math.round(1732 / 10.0). So the method rounds it like 173.0. Then multiplying it with 10 (Math.round( 1732 / 10.0) * 10) gives the rounded down answer, which is 173.0 will then be casted to int.
Use Precision (Apache Commons Math 3.1.1)
Precision.round(double, scale); // return double
Precision.round(float, scale); // return float
Use MathUtils (Apache Commons Math) - Older versions
MathUtils.round(double, scale); // return double
MathUtils.round(float, scale); // return float
scale - The number of digits to the right of the decimal point. (+/-)
Discarded because method round(float,
scale) be used.
Math.round(MathUtils.round(1732, -1)); // nearest ten, 1730
Math.round(MathUtils.round(1732, -2)); // nearest hundred, 1700
Math.round(MathUtils.round(1732, -3)); // nearest thousand, 2000
Better solution
int i = 1732;
MathUtils.round((double) i, -1); // nearest ten, 1730.0
MathUtils.round((double) i, -2); // nearest hundred, 1700.0
MathUtils.round((double) i, -3); // nearest thousand, 2000.0
You could try:
int y = 1732;
int x = y - y % 10;
The result will be 1730.
Edit: This doesn't answer the question. It simply removes part of the number but doesn't "round to the nearest".
At nearest ten:
int i = 1986;
int result;
result = i%10 > 5 ? ((i/10)*10)+10 : (i/10)*10;
(Add zero's at will for hundred and thousand).
why not just check the unit digit...
1. if it is less than or equal to 5, add 0 at the unit position and leave the number as it is.
2. if it is more than 5, increment the tens digit, add 0 at the unit position.
ex: 1736 (since 6 >=5) the rounded number will be 1740.
now for 1432 (since 2 <5 ) the rounded number will be 1430....
I hope this will work... if not than let me know about those cases...
Happy Programming,
very simple. try this
int y = 173256457;int x = (y/10)*10;
Now in this you can replace 10 by 100,1000 and so on....
Its very easy..
int x = 1234;
int y = x - x % 10; //It will give 1230
int y = x - x % 100; //It will give 1200
int y = x - x % 1000; //It will give 1000
The above logic will just convert the last digits to 0. If you want actual round of//
For eg. 1278 this should round off to 1280 because last digit 8 > 5 for this i wrote a function check it out.
private double returnAfterRoundDigitNum(double paramNumber, int noOfDigit)
{
double tempSubtractNum = paramNumber%(10*noOfDigit);
double tempResultNum = (paramNumber - tempSubtractNum);
if(tempSubtractNum >= (5*noOfDigit))
{
tempResultNum = tempResultNum + (10*noOfDigit);
}
return tempResultNum;
}
Here pass 2 parameters one is the number and the other is position till which you have to round off.
Regards,
Abhinav
I usually do it this way:
int num = 1732;
int roundedNum = Math.round((num + 9)/10 * 10);
This will give you 1740 as the result.
Hope this will help.
int val2 = 1732;
val2 = (int)(Math.rint((double) i / 10) * 10);
The output is:1730
Have you looked at the implementation of Mathutils.round() ? It's all based on BigDecimal and string conversions. Hard to imagine many approaches that are less efficient.
Without using any math utils, rounding could be achieved to any unit as below:
double roundValue (double input, double toNearest){
//toNearest is any rounding base like 10, 100 or 1000.
double modValue = input % toNearest;
System.out.println(modValue);
if(modValue == 0d){
roundedValue = input;
}
else
{
roundedValue = ((input - modValue) + toNearest);
}
System.out.println(roundedValue);
return roundedValue;
}

Categories