Division operation is giving me the wrong result [duplicate] - java

This question already has answers here:
Why does integer division code give the wrong answer? [duplicate]
(4 answers)
Closed last year.
I'm trying to divide one number by another in Processing, and I keep getting the wrong answer.
float a;
a = 3/2;
println(a);
gives me
1.0
when then answer should be 1.5.
Trying a different number,
float a;
a = 2/3;
println(a);
gives me
0.0
when the answer should be 0.666666....
Is there something I'm missing? I looked over the Processing documentation for division and it seems like I'm using the right syntax.

Like others have said, you're using integer division.
Remember that int values can't hold decimal places. So if you do a calculation that would result in decimal places, those values are truncated and you're left with only the whole number part (in other words, the integer part).
int x = 1;
int y = 2;
int z = x/y; //0
int x = 5;
int y = 2;
int z = x/y; //2
You're using int literal values (digits like 2 and 3), and those don't have decimal places, so Processing treats them like int values, and they obey the above rules.
If you care about the decimal places, then either store them in float or double variables:
float x = 1;
float y = 2;
float z = x/y; //.5
float x = 5;
float y = 2;
float z = x/y; //2.5
Or just use float literals by adding a decimal part:
float a = 2.0/3.0;
Processing now knows that these are float values, so you'll keep the decimal places.

Perhaps Processing is interpreting both 3 and 2 as integers. And, since you are dividing one integer by another, it is giving you integer division.
Try changing one or both to 3.0 and/or 2.0 instead.

Your division in interpreted as an integer division and will most probably follow Java integer division rules (since Processing seem to be based on Java).
Java inherits most of its division rules from C, these being explained in more details in a specific question/answer here.

Related

Double to int rounding normal way from .5 [duplicate]

This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 9 years ago.
I'm making calculation and for that I'm using the following expression:
Player.targetx = (int) (((e.getX() - Frame.x)/(Screen.myWidth/World.worldWidth))-8);
For example:
if the values are (((103 - 40)/(1184/15))-8) the double answer is around -7.20186. Player.targetx still gets value of -8.
Why's that? I would like to make it so that -7.5 gives me answer of -8 and anything like -7,499999 gives answer of -7.
Casting to int always truncates towards 0. To round, you can use Math.round() instead. However, that always rounds halves up:
class Test {
public static void main(String[] args) {
System.out.println(Math.round(-7.7)); // -8
System.out.println(Math.round(-7.5)); // -7
System.out.println(Math.round(-7.2)); // -7
System.out.println(Math.round(+7.2)); // 7
System.out.println(Math.round(+7.5)); // 8
System.out.println(Math.round(+7.7)); // 8
}
}
Are you sure you want to round halves away from zero? If so, Math.round() won't quite do what you want. You could write your own method though:
public static long customRound(double x) {
return x >= 0 ? (long) (x + 0.5)
: (long) (x - 0.5);
}
This will always round away from zero, by either adding or subtracting 0.5 first (depending on the sign) and then truncating towards 0. That produces the same values as before, except that -7.5 is rounded to -8.
EDIT: I suspect the remaining problem is almost certainly due to the division being performed in integer arithmetic. We don't know the types of any of your values, but I suspect they're all int, which would lead to that problem. If you make either of the operands of the division double, it will perform the division in double arithmetic instead. The easiest way to do that - which would also increase readability - is probably to extract some of the expressions to separate variables, and cast where necessary:
double xDifference = e.getX() - Frame.x;
double widthRatio = Screen.myWidth / (double) World.worldWith;
double x = (xDifference / widthRatio) - 8;
Player.targetx = (int) Math.round(x);
If that still doesn't work, at least you'll have a much easier time seeing what's wrong.
The final cast to int causes the result to be rounded. Try changing that cast to double. Or maybe consider using a DecimalFormat for more precise formatting.

Java percent of number [duplicate]

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;

why is java math.round always rounding down? [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 9 years ago.
I have a number of fields which take inputs, a process which happens and then fields that show the output. My issue is that for some reason math.round seems to be always rounding down instead of to the nearest integer.
Here is an example
private void method(){
int X= Integer.parseInt(XjTF.getText());
int Y= Integer.parseInt(YjTF.getText());
float Z =(X+Y)/6;
int output = Math.round(Z);
OutputjTF.setText(Integer.toString(output)+" =answer rounded to closest integer");
}
Your X and Y variables are int, so Java performs integer division, here when dividing by 6. That is what is dropping the decimal points. Then it's converted to a float before being assigned to Z. By the time it gets to Math.round, the decimal points are already gone.
Try casting X to float to force floating point division:
float Z =((float) X + Y)/6;
That will retain the decimal information that Math.round will use to properly round its input.
An alternative is to specify a float literal for 6, which will force the sum of X and Y to be cast to float before the division:
float Z = (X + Y)/6.0f;
It can't just be 6.0, because that's a double literal, and the Java compiler will complain about "possible loss of precision" when attempting to assign a double to a float.
Here's the relevant quote from the JLS, Section 15.17.2:
Integer division rounds toward 0. That is, the quotient produced for
operands n and d that are integers after binary numeric promotion
(§5.6.2) is an integer value q whose magnitude is as large as possible
while satisfying |d · q| ≤ |n|.

Java math logic error

I have the following code in my project:
int percent = 2;
int count = 10;
int percentagefill = (percent/10)*count;
System.out.println(percentagefill);
Basically what is happening is that, I'm setting two variables, percent and count. I then calculate the percentage fill. For some strange reason the percentage fill is resulting in a 0, when in this case it should be 2. Any ideas why? Thanks in advance.
intdivided by int will still result in int. In this case:
(percent/10)*count
= (2/10)*10
= (0) * 10 <-- 0.2 is rounded down to 0
= 0
You can read this question for reference. Also, here's the Java spec where is says that integer division is rounded towards 0. As for the fix, as long as floating point precision does not become an issue, just use double as PaulP.R.O said.
You could divide by 10.0, or change int percent to double percent in order to force a conversion to double. Otherwise, you are getting integer division, which truncates off the decimal part.
Here is a relevant question: "Java Integer Division, How do you produce a double?"
if you really need the result to be an int, you could do the multiply before the divide to avoid the integer division giving you zero.
int percentagefill = (percent*count)/10;
Change this line:
int percentagefill = (percent/10)*count;
To:
double percentagefill = (percent/10.0)*count;
This will use floating point arithmetic (because of the 10.0 instead of 10), and store the result in a double (which has precision past the decimal point unlike an int).
As others have mentioned, you're losing precision with integer division
The solution depends on your needs: if your result needs to be an integer anyway, multiply first:
int percentagefill = (percent*count)/10;
Could be "good enough" for you (you'll get the correct answer rounded down).
If you need to be able to get fractional answers, you need to convert things to floating point types:
double percentagefill = (percent/10.0)*count;
// ^ the .0 makes this a double,
// forcing the division to be a
// floating-point operation.
It's easy to fix:
int percent = 2;
int count = 10;
double percentagefill = (percent/10.0)*count;
System.out.println(percentagefill);
Dave Newton, your answer should have been an answer. :)
The integer 2 / the integer 10 = 0.
The integer 0 * the integer 10 = 0.
You will need a float or double data type. While working with information, always be weary of chances for the interpreter to make data type assumptions and "casts". println takes an intefer and casts to a string for display is one example.
Most of my work is in php and when working with values, 0, NULL, ERROR can all be different things and can yield unexpected results. Sometimes you may need to explicitly cast a variable to a different data type to get the intended results.
This is so due to the fact that you are using the integer data type when you should be using a floating-point data type such as double. This code should result in 2.0:
double percent = 2;
double count = 10;
double percentagefill = (percent/10)*count;
System.out.println(percentagefill);

Why does integer division code give the wrong answer? [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed last year.
I have a very simple division in Java (it's a product quantity / production per hour), however whenever I make this division I get strange errors:
float res = quantity / standard;
I have tried the above division with several values and I always get errors, however the one that I've tried everywhere else and gotten right was this:
Everywhere in the world:
13.6 = 6800 / 500;
Java:
13.0 = 6800 / 500;
I've researched BigDecimal and BigInteger, however I haven't found a way to create this division with them, is there any other way to do this division in Java without having precision errors??
Any help will be greatly appreciated.
You're dividing integers, which means that you're using integer division.
In integer division the fractional part of the result is thrown away.
Try the following:
float res = (float) quantity / standard;
^^^^^^^
The above forces the numerator to be treated as a float which in turn promotes the denominator to float as well, and a float-division is performed instead of an int-division.
Note that if you're dealing with literals, you can change
float f = 6800 / 500;
to include the f suffix to make the denominator a float:
float f = 6800f / 500;
^
If you concerned about precision I would suggest using double which has more than double the number of digits of precision. However floating point only accurately represents fractions which are a sum or powers of 0.5. This means 0.6 is only approximately represented. This doesn't have to be a problem with appropriate rounding.
double d = (double) 6800 / 500;
or
double d = 6800.0 / 500;
In my case I was doing this:
double a = (double) (MAX_BANDWIDTH_SHARED_MB/(qCount+1));
Instead of the "correct" :
double a = (double)MAX_BANDWIDTH_SHARED_MB/(qCount+1);
hi try this one it may help ful your requirement
double percent=(7819140000l-3805200000l)*100f/7819140000l;
public String format_Decimal(double decimalNumber) {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(5);
nf.setMinimumFractionDigits(2);
nf.setRoundingMode(RoundingMode.HALF_UP);
String x = nf.format(decimalNumber);
return x;
}

Categories

Resources