I've the below SOP:
System.out.println(9 - ((9 / 2) * 2));
From the maths that I learnt in school, it should evaluate to 0.
But I'm getting the output as 1...!!!
I've tried evaluating the same expression in Google the output is 0.
Java evaluates to 1 while according to Maths, it is evaluated to 0. Any explanation?
You're victim of integer division !
Dividing integers in a computer program requires special care. Some
programming languages, treat integer division (i.e by giving the
integer quotient as the answer). So the answer is an integer.
Some logic :
In Java :
9/2 = 4
4*2 = 8
9-8 = 1
In real life :
9/2 = 4.5
4.5*2 = 9
9-9 = 0
To avoid that you can cast one of the argument to double in your division :
System.out.println(9 - (((double)9 / 2) * 2));
Integer division is the culprit here. (9/2) gives 4. And therefore, (9 - (4 * 2)) would evaluate to 1.
Step-by-step:
(9 - ((9 / 2) * 2));
(9 - ((4) * 2)); // integer division
(9 - (8));
1 // final result
9 / 2 is integer division. It evaluates to 4.
You are facing common issue of Integer division.
9 - ((9 / 2) * 2)// here first 9/2=4 (int division)
Now 9-(4*2)=1
That's why you are getting 1
It is done in integer mathematics (see ch. 5.6.2 in Java Language Specification) so:
9 / 2 is = 4
then 4 * 2 is = 8
then 9 - 8 = 1
If you want 0 then do
public class Dec
{
public static void main(String[] args)
{
System.out.println(9.0 - ((9.0 / 2.0) * 2.0));
}
}
There is a short chapter for understanding of "Binary Numeric conversion" located in Java Language specification.
Related
I was trying to execute simple java program to calculate result with expression as: v^2 - u^2 / 2as
that is v*v - u*u / 2*a*s
code is in java 11
int v=16;
int u =5;
int a = 7;
int s = 9;
int res1 = v*v;
int res2 = u*u;
double FunRes1 = Math.pow(v, 2);
double FunRes2 = Math.pow(u, 2);
int part1 = res1 - res2;
int part2 = 2 *a*s;
int result = part1/part2; // = All 4
int AllResult = (v*v-u*u)/2*a*s; // == results
double doubleResult = FunRes1-FunRes2 / 2*a*s; // === have different
double doubleResult2 = (FunRes1-FunRes2) / 2*a*s; // ==== answers (see ss above)
the asnwers of all 4 variable ( result , AllResult , doubleResult1 , doubleResult2 ) are different .
Anyone explain why this happen ?
and What is the correct answers mathematically ?
This is because of operator precedence. If I write something like 2 * 8 / 8 - 6, without further context, it is ambiguous how it should be evaluated. This can lead to different results. For example (2 * 8) / (8 - 6) == 8 but ((2 * 8) / 8) - 6 == -4. To disambiguate, Java uses a list of precedence rules that are common throughout most languages. You can find the complete list here.
For your case the important part is that multiplication and division are applied before addition and subtraction.
Also of note is what happens in the case of operators having equal precedence, which also appears in your example.
When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.
Going back to our example of 2 * 8 / 8 - 6. We can see (from here) that java will evaluate multiplication and division before subtraction. * and / have the same precedence and are both binary operators so we evaluate them left to right. This leaves us with ((2 * 8) / 8) - 6 which is why java evaluates this as -4
System.out.println(2 * 8 / 8 - 6);
-4
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 1 year ago.
Arithmetic Divide operator / returns the Quotient while Arithmetic modulus operator % returns the Remainder. What can be the reason when divide operator is used, it returns 0 value and modulus operator % returns 1. The expression is 1/10 and 1%10.
Note: I am using data type Integer: "int"
Like you said modulus is returning the remaining of a division.
As example:
1 % 10 = 0 R 1 <- This is the value Java returns
15 % 10 = 1 R 5 <- Here it returns 5 because it couldn't divide anymore
And 1 / 10 returns 0 because you are only using Integers. If you doesn't use a floating point number it doesn't return one and rounds down the result.
So if you want a floating point number you will need something like that:
System.out.println(1 / 10); // -> 0
System.out.println((float) 1 / 10); // -> 0.1 //You can also use double for casting
System.out.println(1.0 / 10); // -> 0.1
System.out.println(1 / 10.0); // -> 0.1
System.out.println(1.0 / 10.0); // -> 0.1
Well, It has nothing to do with coding.
We can simply understand it by solving basic maths.
As we know:
Dividend / Divisor == > we get 2 Answers
Quotient and Remainder
If the Remainder is 0, the Dividend is completely divided by Divisor
with parts of Quotient.
As in your suggested example,
1/10 actual Answer is 0.1 which is a float,
In your Java code, you must be looking for the integer value, which practically is not possible.
And obviously, 1%10 will give you 1,
as 10 as divisor can not divide 1 as a dividend.
You can try it with a float variable. I hope you will get your expected results.
The following expression evaluates to 14.
int a=4;
int b=6;
int c=1;
int ans= ++c + b % a - (c - b * c);
System.out.print(ans);
This is how i calculate this
1. (c - b * c) // since bracket has highest preference
ans : -5
2. ++c //since unary operator has next highest preference
ans : 2
3. b%a // % has higher preference than + and -
ans : 2
Therefore, 2 + 2 - (-5) = 9
As you can see I'm getting 9 as the value. Not sure what's wrong in my way of calculation (pretty sure I'm gonna end up looking stupid)
Edit : I refered to the below link for precedence and association.
https://introcs.cs.princeton.edu/java/11precedence/
Can someone explain the difference between level 16 and level 13 parentheses? I thought level 13 parentheses is used only for typecasting. That is why i considered level 16 parenthesis for evaluating the expression.
Evaluation order is not the same as precedence. Java always evaluates left-to-right (with a minor caveat around array accesses).
Effectively, you are evaluating the following expression, because the very first thing that happens is the pre-increment of c:
2 + 6 % 4 - (2 - 6 * 2)
Precedence then describes how the values are combined.
As you are using pre-increment operator on c. So, after applying increment on c the value of c will be 2. Now :
(c - b * c) will be evaluated to (2 - 6 * 2)= -10
So, the final expression will be 2 + 2 - (-10) = 14
This question already has answers here:
math.random, only generating a 0?
(4 answers)
Closed 2 years ago.
I've been trying to create a class to roll dice for games, and my code for one aspect of it is:
public int[] yahtzeeRoll() {
int[] rolls1 = new int[6];
for (int i = 0; i < 6; i++) {
rolls1[i] = ((int) Math.random()*6+1);
}
return rolls1;
}
yet, when I call it in the main method, it only returns 1 for each of the values. Why is this? How can I fix my code so that it generates 6 different numbers when I print the array in the main method?
You are casting the double value returned by Math.random() to int before multiplying by 6, and since Math.random() returns a value < 1, casting it to int results in 0.
Change
rolls1[i] = ((int) Math.random()*6+1);
to
rolls1[i] = (int)(Math.random()*6)+1;
The type casting by appending (type) takes precedence over the * 6 bits afterwards. Therefore, the result from Math.random() is always casted into 0 before you multiply it by 6, which turns out to always be 0 as well.
This answer points to this site which explains it quite well.
Either (int) (Math.random() * 6) + 1 or (int) (Math.random() * 6 + 1) would work as you have intended.
Math.random returns a floating point number between 0 and 1 but you are truncating it down to 0 by using (int) type cast before it. Use parentheses around your expression and then prepend (int) to that if you do wish to use integer truncation.
Btw, I think same sequence should be generated at each run if you don't seed the pseudo-random engine, say with current time or something.
Let's look at the expression.
((int) Math.random()*6+1)
Now Math.random() returns a double that is >=0 and <1.
You then cast that result to an int which means it will always become 0.
If you use.
(int)(Math.random()*6+1)
You are taking the double between 0 and 1, multiplying it by 6 (giving 0 ... 6) adding 1 and then casting to an int. This looks more like what you are looking for.
Math.random() returns double value in range [0, 1) (greater than or equal to 0.0 and less than 1.0). Then you cast that double value to int, so it always results in 0. After that you add 1 to it, so the result always remains 1.
You should cast result of multiplication - Math.random() * 6 instead of casting Math.random() return value:
rolls1[i] = (int)(Math.random()*6)+1;
By the way, you should be aware of operators precedence in Java language. You can have a look here: operator precedence to see nice table that shows that casting has a higher priority than multiplication and addition - this is the reason, why (Math.random()*6) is put in parenthesis for casting (this way you avoid casting only Math.random())
PS. There is also a link to table of operator precedence in official Java tutorial, but it doesn't exactly fit to your problem as it doesn't contain operation of casting - this is the reason, why I provided another link firstly.
You can take a clue from the below output presentation which is self explanatory.
Code:
double random = Math.random();
System.out.println("Math.random()>>"+random);
System.out.println("Math.random()*6>>"+random*6);
System.out.println("(int)(Math.random()*6)>>"+(int)(random*6));
System.out.println("Math.random()*6+1>>"+random*6+1); //+1 here is treated as a string by java and will add at the end of the number
System.out.println("(Math.random()*6+1)>>"+(random*6+1)); //number random*6 will be incremented by 1 as enclosing () will treat them as numbers
System.out.println("(int)(Math.random()*6+1)>>"+(int)(random*6+1));
Output:
Math.random()>>0.6793602796545469
Math.random()*6>>4.076161677927281
(int)(Math.random()*6)>>4
Math.random()*6+1>>4.0761616779272811
(Math.random()*6+1)>>5.076161677927281
(int)(Math.random()*6+1)>>5
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.