Java - division of small number by big number - java

I have declared a variable as double. I wanted to do division of two integer and assign the output to that double variable.
But its not considering the values like 0.1 to 0.9. Only when the no is whole number like 4.0 its returning the answer
public static void main(String[] args) throws Exception
{
double itf=0;
a=4100;
b=6076
itf=a/b;
System.out.println("itf:"+itf)
}
Output is itf: 0.0
Pls help..

Most likely the variables a and b are defined as int , which will result in integer division result as 0 and when assigned to double it becomes 0.0. If you define a,b and itf as double then the result should be
0.6747860434496379
instead of
0.0
Try this code:
public static void main(String[] args) throws Exception {
double itf = 0;
double a = 4100;
double b = 6076;
itf = a / b;
System.out.println("itf:" + itf);
}

a and b are both integers, so the result of a/b is also an integer, which is then cast to a double to be stored in itf. To get the correct result, you could either define a and b as doubles, or you could cast at least one of them to double. For instance:
itf = (double)a/b;

Declare a or b as double.
OR
Cast the operation.
itf = (double)(a/b)
OR Cast one of the integers.
itf = ((double)a)/b
OR multiply with 1.0, which is double.
itf = (1.0*a)/b

The reason for your result is that you are using integer division, then assign the result to a double value. This is your code unrolled:
int a = 4100;
int b = 6076;
int temp = a / b;
double itf = temp;
If you want to explicitly use floating point division, you need to tell the compiler that you do by casting at least one (or all to be sure) member of that operation to double or float. Example:
itf = (double)a / (double)b;

Use the foloving cast to at least one operand to double
itf=((double)a)/b;
or
itf=a/((double)b);

double itf = ((double) a / (double) b);

Related

Decimal value issue

I've got a really annoying task to do, and stuck with it.
So: I need to write a function which gives back the value of a floating number after the decimal.
For example: the param would be:5.456-> and the returning value should be:456.
I can not use String (of course this would be easy this way).
Do you have any suggestions?
It requires some steps to do it with primitives like float or double. If you were allowed to use BigDecimal, this would just be one line of code.
Given double d = 5.456;
first, cut off the part before the floating point.
do this by int full = (int)d; which will be 5
the subtract full from it: d-full will now be only the part after the point, so .456
now use a loop to multiply the value by 10 until the "after the point" part is 0.
The special thing here is that when you use double, you have floating point precision issues. That means that d will have the value 0.4560000000000004 in between. To solve that, let's introduce an epsilon.
The full code looks like this:
private static final double EPS = 1e-5;
public static void main(String[] args) {
double d = 5.456;
System.out.println(afterDot(d));
}
private static int afterDot(double d) {
d = getDecimals(d);
while(getDecimals(d) > EPS){ //decimals will likely never be 0 because of precision, so compare with a really small EPS instead of 0
d *= 10;
}
//cast the result to an int to cut off the double precision issues
return (int)d;
}
private static double getDecimals(double d) {
int full = (int) d;
d = d-full;
return d;
}
This prints 456. I am very sure this can be optimized somehow, but it's a working first draft.
What you want is the remainder, multiplied by 10 until the remainder is 0. Using BigDecimal to prevent rounding issues that looks like this:
final BigDecimal input = new BigDecimal("5.456");
BigDecimal x = input.remainder(BigDecimal.ONE);
while (x.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO) > 0) {
x = x.multiply(new BigDecimal(10));
}
System.out.println(x.longValue());
Here are two ways that don't adjust for floating point anomalies.
double s = 5.456;
System.out.println(s%1);
or
System.out.println(s-(int)s);
both print
0.4560000000000004
Or use BigDecimal and adjust the scale and subtract the integer value.
System.out.println(BigDecimal.valueOf(s)
.setScale(3)
.subtract(BigDecimal.valueOf((int)s)));
prints
.456

Rounding double to int using math class

I've been trying to make the unitTotal(double) into an integer by using the rounding method, then assigning the integer to the mark variable. I have been stuck on this question and I don't know what I'm doing wrong. If anyone can explain to me what I'm doing wrong it'd be appreciated. Thank you
public class GradeCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double unitTotal;
int mark;
String grade;
System.out.println("Enter your unit total score");
unitTotal = sc.nextDouble();
Math.round(unitTotal);
mark = unitTotal;
You should assign the rounding result to the variable:
mark = (int) Math.round(unitTotal);
Do note that Math class suggests to round double to long. By casting to int you are potentially loosing precision.
You could use sc.nextFloat(); instead. Then you can use Math.round(float a) that returns int and assign it to mark:
mark = Math.round(sc.nextFloat());
If what you want is a method for rounding a double to the nearest whole number then I have an idea, though it's not using a library method.
public int round(double value) {
int cutDecimals = (int) value; // This cuts the decimals entirely, rounding down
double decimals = value - ((double) cutDecimals); // Gives only the decimals
if(decimals < 0.5) return cutDecimals; // If the decimals is less than 0.5 we return the rounded down number
else return cutDecimals + 1; // If the decimals is over 0.5 we round up
}
According to Docs, Math.round method returns long when passing value is double and returns int when passing value is float.
Change type of mark to long or you need to convert long into int manually. Keep in mind that it could throw an exception if return value is more than Integer.MAX_VALUE.
Also, you need to store return value into variable.
Math.round(unitTotal);
replace with
mark = Math.round(unitTotal);
HTH.

Rules of casting from int to double [duplicate]

I was writing this code:
public static void main(String[] args) {
double g = 1 / 3;
System.out.printf("%.2f", g);
}
The result is 0. Why is this, and how do I solve this problem?
The two operands (1 and 3) are integers, therefore integer arithmetic (division here) is used. Declaring the result variable as double just causes an implicit conversion to occur after division.
Integer division of course returns the true result of division rounded towards zero. The result of 0.333... is thus rounded down to 0 here. (Note that the processor doesn't actually do any rounding, but you can think of it that way still.)
Also, note that if both operands (numbers) are given as floats; 3.0 and 1.0, or even just the first, then floating-point arithmetic is used, giving you 0.333....
1/3 uses integer division as both sides are integers.
You need at least one of them to be float or double.
If you are entering the values in the source code like your question, you can do 1.0/3 ; the 1.0 is a double.
If you get the values from elsewhere you can use (double) to turn the int into a double.
int x = ...;
int y = ...;
double value = ((double) x) / y;
Explicitly cast it as a double
double g = 1.0/3.0
This happens because Java uses the integer division operation for 1 and 3 since you entered them as integer constants.
Because you are doing integer division.
As #Noldorin says, if both operators are integers, then integer division is used.
The result 0.33333333 can't be represented as an integer, therefore only the integer part (0) is assigned to the result.
If any of the operators is a double / float, then floating point arithmetic will take place. But you'll have the same problem if you do that:
int n = 1.0 / 3.0;
The easiest solution is to just do this
double g = (double) 1 / 3;
What this does, since you didn't enter 1.0 / 3.0, is let you manually convert it to data type double since Java assumed it was Integer division, and it would do it even if it meant narrowing the conversion. This is what is called a cast operator.
Here we cast only one operand, and this is enough to avoid integer division (rounding towards zero)
The result is 0. Why is this, and how do I solve this problem?
TL;DR
You can solve it by doing:
double g = 1.0/3.0;
or
double g = 1.0/3;
or
double g = 1/3.0;
or
double g = (double) 1 / 3;
The last of these options is required when you are using variables e.g. int a = 1, b = 3; double g = (double) a / b;.
A more completed answer
double g = 1 / 3;
This result in 0 because
first the dividend < divisor;
both variables are of type int therefore resulting in int (5.6.2. JLS) which naturally cannot represent the a floating point value such as 0.333333...
"Integer division rounds toward 0." 15.17.2 JLS
Why double g = 1.0/3.0; and double g = ((double) 1) / 3; work?
From Chapter 5. Conversions and Promotions one can read:
One conversion context is the operand of a numeric operator such as +
or *. The conversion process for such operands is called numeric
promotion. Promotion is special in that, in the case of binary
operators, the conversion chosen for one operand may depend in part on
the type of the other operand expression.
and 5.6.2. Binary Numeric Promotion
When an operator applies binary numeric promotion to a pair of
operands, each of which must denote a value that is convertible to a
numeric type, the following rules apply, in order:
If any operand is of a reference type, it is subjected to unboxing
conversion (§5.1.8).
Widening primitive conversion (§5.1.2) is applied to convert either or
both operands as specified by the following rules:
If either operand is of type double, the other is converted to double.
Otherwise, if either operand is of type float, the other is converted
to float.
Otherwise, if either operand is of type long, the other is converted
to long.
Otherwise, both operands are converted to type int.
you should use
double g=1.0/3;
or
double g=1/3.0;
Integer division returns integer.
Make the 1 a float and float division will be used
public static void main(String d[]){
double g=1f/3;
System.out.printf("%.2f",g);
}
The conversion in JAVA is quite simple but need some understanding. As explain in the JLS for integer operations:
If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6).
And an example is always the best way to translate the JLS ;)
int + long -> long
int(1) + long(2) + int(3) -> long(1+2) + long(3)
Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.
short + int -> int + int -> int
A small example using Eclipse to show that even an addition of two shorts will not be that easy :
short s = 1;
s = s + s; <- Compiling error
//possible loss of precision
// required: short
// found: int
This will required a casting with a possible loss of precision.
The same is true for the floating point operators
If at least one of the operands to a numerical operator is of type double, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type double. If the other operand is not a double, it is first widened (§5.1.5) to type double by numeric promotion (§5.6).
So the promotion is done on the float into double.
And the mix of both integer and floating value result in floating values as said
If at least one of the operands to a binary operator is of floating-point type, then the operation is a floating-point operation, even if the other is integral.
This is true for binary operators but not for "Assignment Operators" like +=
A simple working example is enough to prove this
int i = 1;
i += 1.5f;
The reason is that there is an implicit cast done here, this will be execute like
i = (int) i + 1.5f
i = (int) 2.5f
i = 2
1 and 3 are integer contants and so Java does an integer division which's result is 0. If you want to write double constants you have to write 1.0 and 3.0.
I did this.
double g = 1.0/3.0;
System.out.printf("%gf", g);
Use .0 while doing double calculations or else Java will assume you are using Integers. If a Calculation uses any amount of double values, then the output will be a double value. If the are all Integers, then the output will be an Integer.
Because it treats 1 and 3 as integers, therefore rounding the result down to 0, so that it is an integer.
To get the result you are looking for, explicitly tell java that the numbers are doubles like so:
double g = 1.0/3.0;
(1/3) means Integer division, thats why you can not get decimal value from this division. To solve this problem use:
public static void main(String[] args) {
double g = 1.0 / 3;
System.out.printf("%.2f", g);
}
public static void main(String[] args) {
double g = 1 / 3;
System.out.printf("%.2f", g);
}
Since both 1 and 3 are ints the result not rounded but it's truncated. So you ignore fractions and take only wholes.
To avoid this have at least one of your numbers 1 or 3 as a decimal form 1.0 and/or 3.0.
My code was:
System.out.println("enter weight: ");
int weight = myObj.nextInt();
System.out.println("enter height: ");
int height = myObj.nextInt();
double BMI = weight / (height *height)
System.out.println("BMI is: " + BMI);
If user enters weight(Numerator) = 5, and height (Denominator) = 7,
BMI is 0 where Denominator > Numerator & it returns interger (5/7 = 0.71 ) so result is 0 ( without decimal values )
Solution :
Option 1:
doubleouble BMI = (double) weight / ((double)height * (double)height);
Option 2:
double BMI = (double) weight / (height * height);
I noticed that this is somehow not mentioned in the many replies, but you can also do 1.0 * 1 / 3 to get floating point division. This is more useful when you have variables that you can't just add .0 after it, e.g.
import java.io.*;
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 15;
System.out.println(1.0 * x / y);
}
}
Do "double g=1.0/3.0;" instead.
Many others have failed to point out the real issue:
An operation on only integers casts the result of the operation to an integer.
This necessarily means that floating point results, that could be displayed as an integer, will be truncated (lop off the decimal part).
What is casting (typecasting / type conversion) you ask?
It varies on the implementation of the language, but Wikipedia has a fairly comprehensive view, and it does talk about coercion as well, which is a pivotal piece of information in answering your question.
http://en.wikipedia.org/wiki/Type_conversion
Try this out:
public static void main(String[] args) {
double a = 1.0;
double b = 3.0;
double g = a / b;
System.out.printf(""+ g);
}

Converting a variable from Double to Int

Lets say that I have variable tmp which is a double, and I want to convert tmp to an int, but still have the variable called tmp. How would I do this?
Thanks
You can't have the same variable as both an int and a double.
You can have this though:
double d = 0.1d;
int i = (int) d;
d = (double) i;
System.out.println(d);
Basically you first cast your double to an integer, losing the fraction. Afterwards you cast it to a double again and assign it to your d variable. You don't have to explicitly do the casting from int to double because it is a widening conversion, but it makes it more clear what happens.
The end result is that your d variable now has a value that can be precisely interpreted by an integer but on the other hand you also, well, basically threw away your fraction. Your variable did not change its type, however.
You can write this less verbosely like this:
double d = (int) 0.1d;

Java double x 10/4=2?

I am new to Java and I would like to know why when you have double 10/4 you get 2? Does double always have to have decimals in order to get the right answer? Thanks.
public class Super {
public static void main(String[] args){
double x = 10/4;
System.out.println(x);
}
}
You are performing integer division before assigning the result. Integer division results in an int, the truncated result 2. To force floating point calculation and get 2.5, use double literals:
double x = 10.0 / 4.0;
or cast one to a double:
double x = (double) 10 / 4;
You are dividing with integers. You can declare those as doubles the following way (or use f for floats):
double x = 10d/4d;
System.out.println(x);
Integer division. Even though you're assigning the result to a double, you're still dividing two integers (10 and 4) so you get an integer result (floor of the actual result).
You can fix this by having one or both operands be a floating point value, for example like this:
double x = 10.0/4;
or by using type casting:
double x = (double)10/4;
Replace it by:
double x = 10.0/4.0;
Double always takes in a decimal. So it would have to be
public class Super {
public static void main(String[] args){
double x = 10.0/4.0;
System.out.println(x);
}
}
For double you need to use the following
10d/4d
Then the output is going to be 2.5 Otherwise you are just gonna end up diving two integers
The right side ofter the '=' is an integer expression, which gets converted to double only after it's calculated. So it calculates 10/4 as an integer, 2, and then converts that number to double. If you want it as a double from the beginning you have to write
double x = 10.0 / 4.0;
Only numbers that cannot be read as integer will be treated as double. Or even simpler
double x = 2.5; // :-)

Categories