Java dividing incorrectly [duplicate] - java

This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 7 years ago.
I am using Java 7
I am trying to get a double from dividing two integer:
double chance = 1/main.getConfig().getInt("dailygiftItems.items."+key+".chance");
double w = Math.random();
System.out.println("Pulled: "+main.getConfig().getInt("dailygiftItems.items."+key+".chance"));
System.out.println("itemChance: "+chance);
System.out.println("itemRand: "+w);
if(!(w < chance))continue;
However chance is returning 0. As you can see I have debugged all the values here is what they bring me:
Pulled: 5
itemChance: 0
itemRand: some random double (working correctly)
I was thinking if I did my math wrong and 5/1 is not 0.2 so I used a calculator. However the calculator returned to me 0.2.
I then tested on something simpler testing the same problem:
public class Test
{
public static void main(String[] args)
{
double chance = 1/5;
double w = Math.random();
System.out.println("Chance: "+chance);
System.out.println("Random: "+w);
if(!(w < chance))
{
System.out.println("no");
return;
}
System.out.println("yes");
}
}
This produced the same result as:
Chance: 0
w: some random double (working)
My questions: Why is java not dividing this correctly, and how can I fix it?

Use double chance = 1./main.getConfig().getInt("dailygiftItems.items."+key+".chance");
The . after 1 will force the compiler into considering this is a floating point (double) operation.

Related

Why casting give me these weird results Java? [duplicate]

This question already has answers here:
Why converting from float to double changes the value?
(9 answers)
Closed 2 years ago.
This is the code
public static void main(String[] args) {
double x=5.6556464566546546546556465465465;
float y=(float)x;
double z= 1+y;
System.out.println(x+"\n"+y+"\n"+z);
}
}
and this is the output
5.6556464566546545
5.6556463
6.655646324157715
I can understand the value of x and y but z from where it got those fractional numbers after the 3??!
Thank you very much
Floats are an approximation of the actual number in Java, due to the way they're stored. If you need exact values, use a BigDecimal instead.

How to round float to one decimal point without using DecimalFormat class in java? [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 6 years ago.
I was reading my old notes and found a question where a number with two decimal point is converted to a single decimal point. I looked around for answer and couldn't find it. I cannot keep it string as I have to return as a float and compare it.
Math.round was rounding it bad and ceil and floor was giving me error.
I came up with this solution.
public class floatRounding{
public static void main(String[] args){
//System.out.println(temperature((float)32.34));
// System.out.println(temperature((float)32.35));
if (temperature((float)32.34)<temperature((float)32.35)){
System.out.println("Here");
}
}
public static float temperature(float t){
float newt;
//newt=Math.round(t);
String tem=String.format("%.1f",(t+.009));
newt=Float.parseFloat(tem);
System.out.println(newt);
return newt;
}
}
Is there a better solution if I am not using decimal format like in this solution
How to round a number to n decimal places in Java
Thanks in advance. Please forgive if its a dumb question.
You could do something like this:
double x = 1.234;
double y = Math.round(x * 10.0) / 10.0; // => 1.2
System.out.println(y);
This rounds the decimal to the one decimal point, the code is much shorter. Hope this helps, if so accept the answer :)

Why does a fraction stored in a double become a whole number upon outputting to screen? [duplicate]

This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 6 years ago.
So, I have this code which is the beginning of an RSA-encrypter (current math class). Now I'm still in the beginning stages and I notice that when I try to make an array of doubles, they all come out to the screen as whole numbers, what's going on here ?
As you can see in the code I divide the multiples of 7 by 40 and it should come out as fractions (7 / 14 = 0.175 for example) but instead as 0.0.
Help
import java.util.*;
public class Encryption {
static double[] ads = new double[200];
public static void main(String args[]){
for(int i = 0; i < 200; i++){
ads[i] = (7 * i) / 40;
}
for(int i = 0; i < ads.length; i++){
System.out.println(ads[i]);
}
}
}
It's because you're storing an integer into the array in the first place.
Consider this line:
ads[i] = (7 * i) / 40;
In the expression on the right, you first multiply i by 7, then divide it by 40. i is an integer. So, let's say i == 1. Then, 7 * i == 7, which is still an integer. Both 7 and 40 are integers, so when you evaluate 7 / 40, you get integer division. Integer division always rounds down. When the result gets stored into ads[i], it gets converted to a double, but by that point it's already been rounded down.
Try changing this line to the following:
ads[i] = (7 * i) / 40.0;
This works because 40.0 is a double, not an int.
In unrelated news, if you're using double to implement RSA, you're probably doing something wrong. Doubles aren't infinitely precise, and will screw up your result.

Inaccuracy in value inputed [duplicate]

This question already has answers here:
Strange floating-point behaviour in a Java program [duplicate]
(4 answers)
How to resolve a Java Rounding Double issue [duplicate]
(13 answers)
Why is comparing floats inconsistent in Java?
(8 answers)
Closed 8 years ago.
public void Calculate(double value){
int quarter, dime, nickel, remainder;
value *= 100;
System.out.println(value);
This is part of a simple coin counter program (I'm learning programming)--I have value set to 2.26 but found that I didn't get the desired answer, so I did System.out.println(value) to pinpoint where I am not getting the value expected. With value = 2.26, I should get 226 but instead I get 225.99999999999997, which throws off the entire program.
You can add casting to float, then it works fine
public static void main(String[] args) {
Calculate ((float) 2.26);
}
public static void Calculate(float value){
int quarter, dime, nickel, remainder;
value *= 100;
System.out.println(value);
}
Here is the solution
public void Calculate(double value){
int quarter, dime, nickel, remainder;
value *= 100;
System.out.println(round(value,0));
}
You are using double. Double stores many places after decimal in memory so 2.26 is an approximation of a value which is like 2.25999999...
You must round your results to two places of decimal for accurate value.
If you want to know how to round numbers refer to this answer enter link description here

Java math isnt making sense [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Dividing two integers in Java gives me 0 or 100?
(5 answers)
Closed 9 years ago.
OK so this is a problem in a larger piece of code which does'nt seem to make sense. below is the code which is the problem... It prints Ratio = 0.0 the console when launched it should be equal to ~0,348.
public class MathTest {
public static void main(String[] args) {
double ratio = 29511 / 84812;
System.out.println("Ratio = "+ ratio);
}
}
Edit:
What if the code is this:
public class MathTest {
public static void main(String[] args) {
int int1 = 7;
int int2 = 13;
double double1 = int1/int2;
System.out.println("double1 = "+ double1);
}
}
It again prints "0.0".
You have unwittingly used integer division when you say 29511 / 84812, which in Java, loses the decimal points. Use double literals (with .0 added) instead:
double ratio = 29511.0 / 84812.0;
Other solutions that work here:
Cast one of them to a double: (double) 29511 / 84812
Use 'D' as another way to indicate a Java double literal: 29511D / 84812D
You are doing integer division because 29511 and 84812 are ints. The result of the division is 0, and you are saving it as a double so it becomes 0.0.
To fix this, cast one of the operands on the right side of the assignment to a double.
double ratio = (double)29511 / 84812;
Replace double ratio = 29511 / 84812 with double ratio = 29511.0 / 84812.0;
It make perfect sense. You are dividing two integers to get an integer. This means 0 in this case.

Categories