Java math isnt making sense [duplicate] - java

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.

Related

Dividing two integers and rounding up result to nearest integer [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 3 years ago.
I have two int numbers a, b always >= 0. I want to divide a by b and return the rounded up percentage to the nearest integer.
Example: 18/38 should return 47 and 13/38 should return 34.
How can I accomplish this?
I tried the following but it didn't work
c = Math.round(a/b) * 100;
Since a and b are integers, a/b will use integer division, and only return the "whole" part of the result. Instead, you should multiply a by 100.0 (note the .0, which makes it a double literal!) to use floating-point division, and then ceil the result, and truncate it to an int:
c = (int) Math.ceil(100.0 * a / b);
public static void main(String[] args){
int a=18,b=38,c=0;
c = (int) Math.round(100.0 * a / b);
System.out.println(c);
}
As #Mureinik said that a and b are integers,they will use integer division.
you should multiply 100 by a like above. and keep using .round instead of .ceil inorder to get 47 as output which is intended .ceil will give you 48 as output.
c = (int) Math.round(100.0 * a / b);
This should give desired result.
You need to do follow things to get the result
Double res= Double.valueof(a/b);
DecimalFormat decimalFormat = new DecimalFormat("#.00");
String num= decimalFormat.format(res);
Int finalResult = Integer.valueof(num)*100;
Thanks

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.

Java casting (cast operator expressions) [duplicate]

This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 6 years ago.
The question require me to write a Java program to show the results of the following cast operator expressions:
(double) (23 / 14) + 7.65
My Code:
public class op {
public static void main(String [] args) {
int num = 23/14;
double r1 = (double) num;
double result = r1 + 7.65;
System.out.println("Results: "+ result);
}
}
I don't think I have done correctly, what are the problems of my code?
By the way, can someone tell me what are the differences between long, double, int, float? How do we know when to use these primitive data types? I read an explanation here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
but is there any 'human-version' of the explanation?
Thank you for your help.
The problem is due to the used types.
Since you divide two integers (23 and 14), the result is considered and int as well. Therefor, 23/14 = 1.642857142857143, which is truncated to fit in an int result, more specifically, 1.
result is the sum of 1 (int) and 7.65 (double). Since one of them is a double, to other is converted to the "upper" type as well (double) and the operation becomes 1.0+7.65 = 8.65.
The result is correct, because you asked the result of (double) (23 / 14) + 7.65 which means the result of casting the result of the operations in brackets to double summed with 7.65. Which is 8.65 as previously explained.
If you want to use a division using doubles, consider:
double r1 = 1.0 * 23/14;
Lets see step-by-step:
int num = 23/14; // int division of 23/14 results in 1
So, here num = 1
When you cast num to double value of r1 is setted to 1.0.
double result = r1 + 7.65; //1.0 + 7.65 = 8.65
ok, int is short term for INTEGER which are natural numbers that we use normally but with no decimal places and if your number has some value in between roughly -2 billion to +2 billion. if your range exceeds that and you still want an integer then go for long data type.
floats are for decimal values like 3.147 with a range of +10*38 to -10*38 or so, but if your range exceeds this(practically this happens rarely) go for double.
coming to the code you put here , if you divide a int by another int (like 23/14) you get only get the integer part of the answer(only '1' in 23/14=1.642...) , next when you cast it to double you get 1.0 and next you are going to add that to 7.65 which will make the ultimate answer as 8.65 hope this answers your Q....
You could change this int num = 23/14
to double num = ((double) 23)/14
or double num = (23 * 1.0)/14

Java - double constant number of decimal places [duplicate]

This question already has answers here:
fixed point arithmetics in java with fast performance
(4 answers)
Closed 7 years ago.
I have two double variables:
double a = 1.109
double b = 5.0E-5;
But b is changable and I want to achieve fixed numbers of decimal places depending of b number, for example above I want achieve this result:
Result = 1.10900
But not only print, I need to send it to other method and my double must have fixed numbers of decimal places like in example.
It sounds like you want arbitrary precision on the actual value (as opposed to just output). double doesn't give you that. BigDecimal does though. Its BigDecimal(String) constructor sets the value and the scale (number of places to the right of the decimal) from a string, so:
BigDecimal d = new BigDecimal("1.10900");
BigDecimal then gives you various math operations to stay within that scale, with various rounding options.
If at some point you need to get the double value of the BigDecimal, you can use its doubleValue method. But note that at that point, again, you don't have a fixed number of places to the right of the decimal anymore.
Here's an example contrasting BigDecimal and double (Live Copy):
import java.math.*;
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
BigDecimal bd = new BigDecimal("1.10900");
bd = bd.divide(new BigDecimal("27"), BigDecimal.ROUND_HALF_DOWN);
System.out.println("1.109 / 27 using BigDecimal to five places: " + bd);
double d = 1.109;
d = d / 27.0;
System.out.println("1.109 / 27 using double: " + d);
}
}
Output:
1.109 / 27 using BigDecimal to five places: 0.04107
1.109 / 27 using double: 0.041074074074074075
Try using a number formatter:
NumberFormat formatter = new DecimalFormat("#0.00000");
double a = 1.109;
double b = 5.0E-5;
System.out.println(a);
System.out.println(b);
Output:
1.10900
0.00005
A simple solution is to round the result as needed. This is not only faster than using BigDecimal it can be less error prone as Java doesn't have language support for BigDecimal making it harder to write/read and validate. A simple method for rounding half up for 5 decimal spaces is
public static double round5(double d) {
final double factor = 1e5;
return d > Long.MAX_VALUE / factor || d < -Long.MAX_VALUE / factor ? d :
(long) (d < 0 ? d * factor - 0.5 : d * factor + 0.5) / factor;
}
Note: when you print the double you will still need to specify the number of decimal places you need e.g.
System.out.printf("%.5f", value);
Use java printf-like routine (note it produces platform dependent decimal separators):
String.format("%.5f", a)

Java dividing incorrectly [duplicate]

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.

Categories