Double not storing proper value - java

The code that I have,
public static void main(String[] args) {
int x = 27;
int y = 5;
double z = x / y;
System.out.println(" x = " + x + " y = "+y +" z = "+z);
}
In the above code I know that to print out the decimal place .4 for the variable z we have to use printf, but my question is why does the variable z is not storing the 5.4 and just storing 5?
I mean int / int then the out put is stored in a double, which is perfectly capable of holding decimal values but it is not, what is the logic?

This is happening because the values that you are dividing with are int and not double and they are not going to output the decimal places, to be more clear take this for example
double z = 27 /5;
same as yours
double z = 27.0/5.0;
now z = 5.4;
So this shows that the datatype that you are performing calculation with also should be the same as the datatype you are expecting the output to be.

You need to cast one of the operands to a double
double z = (double) x / y;
The reason is x / y stand-alone is an int, so it is really evaluating as 5 and then parsing to a double.

You have to cast the integers before you divide I believe.
Like this,
double z = (double) x / (double) y;

What you're doing in the line:
double z = x / y;
is integer division, and then you convert the outcome to double

Related

Double variable with 16+ digits gives error: Integer Number too Large

The following code is designed to factorize a number typed into the variable x.
public class testMod{
public static void main(String[]args){
double x = 11868681080091051216000;
StringBuilder output = new StringBuilder("1 * ");
for(double y = 2; y <= x; y++){
while (x % y == 0) {
System.out.print("Calculating... \n");
String printNumber = y + " * ";
x = x / y;
output.append(printNumber);
System.out.print(output.substring(0, output.length() - 2) + "\n");
}
}
}
}
The problem is that the compiler treats 11868681080091051216000 as an int, regardless of the attempt to assign it to a double. As such, it's out of range.
To specify a double literal, you can simply append D to the end – but do note that you'll lose precision this way:
double x = 11868681080091051216000D;
System.out.println(x); // prints 186868108009105E22
If you need the full precision, you can use a BigInteger instead, but you'll still need to specify that number in expressions that Java can handle, such as a product of its factors.

Force integer division on a double?

I have
x /= y;
Where x & y are both double
I would like x to be the integer part of x/y , how do I do this?
I have tried
x /= y;
x = x.intValue();
But am receiving a double cannot be dereferenced error in TIO which I presume means the double x does not have that method
IO x = x\y: Carry out float division then round towards -∞
NB all I'm after is to change this code to add in floor division with \
x = java.lang.Math.floor(x/y);
Relying on some Math function is arguably the best choice. "Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer."
If you need the symmetric version (truncation towards zero), you'll have to handle negative quotients:
floor(abs(x/y))*signum(x/y)
Force integer division on a double?
To force integer division, use int or long (for the calculation part); long would probably be the better choice:
x = (double)((long)x / (long)y);
That uses an explicit cast back to double for emphasis; you can just write it with the implicit cast back to double if you prefer:
x = (long)x / (long)y;
Do note that (long)y on a non-zero y can result in 0 (for instance, if y is 0.3), which then ends up being division-by-zero and thus a runtime exception.
I would like x to be the integer part of x/y
That's a different question than the title; that's not integer division, that's getting the integer part of the result of floating point division. If that's what you want, just cast the result:
x = (long)(x / y);
...(and of course the long is then implicitly cast back to double) or use Math.floor on it.
I have tried
x /= y;
x = x.intValue();
But am receiving a double cannot be dereferenced error
Right. x is a double, not Double. Primitives (like double) don't have methods, only reference types (like Double) do.
If a smaller data type is assigned to a bigger data type, there'll be no error. But the assignment of bigger to smaller gives error. In this case, you need to make compatible these data types with each other using type conversion ('x = (Type) y'). Converting a double to int is an example of assigning a bigger data type (double) to smaller (int). When we perform this operation, the double variable lost its precision and its "integer part" is assigned to the int variable.
double x = 3, y = 2;
x /= y;
int integerPart = (int) x;
System.out.println(integerPart); // Prints 1
From small to big, the numeric data types are as follows btw:
byte < short < int < long < float < double
Edit: After your last edit I realized what you actually ask. Your first expression was wrong. You don't want to find integer part of the double result of division, you want its floor. Just use java.lang.Math.floor:
double[] x = {-10, -7, 1, 3, 7.1, 9.5};
double[] y = {-10, -7, -1.7, 0.5, 7.1, 9.5};
for (int i = 0; i < y.length; i++) {
for (int j = 0; j < x.length; j++)
System.out.print(Math.floor(x[j] / y[i]) + " ");
System.out.println();
}

Integer is printed out a different value from what it actually is? [duplicate]

This question already has answers here:
How to make the division of 2 ints produce a float instead of another int?
(9 answers)
Closed 8 years ago.
So I have this code:
int x = 435;
int y = x / 2 * 5;
If I calculate y by hand, I get a result of 1087.5. But when I print the integer y out, I get the result 1085. Why is this? Shouldn't it round to either 1088 or 1087?
It's because of integer arithmetic:
int/int = int
So, 435/2 will be
435/2 = 217
And
217*5 = 1085
What can you do? Cast the values as you need:
int y = (int)((float)x / 2 * 5);
or if you want a real result, declare the variable y as float:
float y = (float)x / 2 * 5;
this saves in result of each part as an int
so
435 / 2 == 217
217 * 5 == 1085
int value of x/2=217 and 217 * 5 == 1085 is the reason
you are dividing int value x so result will be int value (int/int=int)
x/2=217
Then
217*5=1085
Try this:
int x = 435;
double y = ((double) x / 2) * 5;
y cannot be int (or else you will lose precision). Moreover, x / 2 will yield you an integer value, hence you need to cast it to double or float
Java is using integer math, this
int x = 435;
int y = x / 2 * 5;
is equivalent to
int x = 435;
int y = x / 2; // <-- 217
y *= 5; // <-- 1085
If you wanted to round the other way try,
int x = 435;
int y = (int) Math.round(((double) x / 2) * 5); // <-- 1088
the answer is correct as -:
435/2 = 217.5 since declared as int it is rounded off to 217
217*5 = 1085
which is the required answer.
When you divide 435 by 2.
It stores 217 not 217.5 and hence after multiplying 217*5= 1085
You are trying to store a float value into INT and hence getting the truncated value.
Also,without brackets, the compiler will start to execute from LHS to RHS one by one according to priority of operator.
Your code
int x = 435;
int y = x / 2 * 5;
is actually performing the following operation.
Assigning x = 435;
Dividing first y = x / 2; // This stores y= 217
And then it multiplies y=y*5; // Finally y= 1085
Using int will truncate 217.5 into 217 and hence you are getting that answer.
Use double or float for storing the kind of answer you want
int x = 435;
double y = y=(x/2)*5
This will get you the required answer.

Converting from JavaScript to Java but not giving same output

I have some lines of code that produces a number after calculation which is currently in JavaScript and here is the code:
if ( y2 != y1 )
{
// calculate rate
var f;
var y;
if ( y2 > y1 )
{
f = cpi[y2] / cpi[y1];
y = y2 - y1;
}
else
{
f = cpi[y1] / cpi[y2];
y = y1 - y2;
}
var r = Math.pow(f, 1/y);
r = (r-1)*100;
r = Math.round(r*100) / 100;
System.out.println( "number: " + r.toFixed(2) + "%." );
}
I converted the above JS code to Java and here is the code:
DecimalFormat decimalFormat = new DecimalFormat("0.##");
if (cpi[to] != cpi[from]) {
double f, y;
if (cpi[to] > cpi[from]) {
f = cpi[to] / cpi [from];
y = to - from;
}
else {
f = cpi[from] / cpi[to];
y = from - to;
}
q = Math.pow(f, 1/y);
q = (q-1)*100;
q = Math.round(q*100)/100;
Toast.makeText(getApplicationContext(), "number: " + String.valueOf(decimalFormat.format(q)), 2000).show();
}
The JavaScript code produces: number: 2.39
While the Java code produces number: 2
Why am I getting two different value? I will post what cpi[to], cpi[from], to and from values are if needed.
In this line
q = Math.round(q*100)/100;
both operands of the division operation are integral, therefore the result is also an integral type. Use 100.0 as the divisor to coerce the result to a double.
what is q type?
try to put 100.0 also
If you devide two integers in java the result is integer. Every operation with double and integer or with two doubles creates double.
1)In this line
1)q = Math.round(q*100)/100;
2)you are deviding two integers, so it has same output as:
2)q = (int) (Math.round(q*100)/100);
3)you can use casting to double for example:
3)q = Math.round(q*100)/(double)100;
4)or using the 100.0 which makes this number double:
4)q = Math.round(q*100)/100.0;
5)this should work too, because first the result of Math.round is converted to double and then devided by 100:
5)q = (double)Math.round(q*100)/100;
6)However this WILL NOT work, because first Math.round is devided by 100 and it creates integer, so the result of this operation is rounded down and AFTER then casted to double. So it will be double but still rounded down, because it was rounded before it becomes double.
6)q = (double)(Math.round(q*100)/100);
Most likely your issue is Math.round(double) returns a long value. So d would contain a long instead of a double at that point.

java program using int and double

I have written a simple Java program as shown here:
public class Test {
public static void main(String[] args) {
int i1 =2;
int i2=5;
double d = 3 + i1/i2 +2;
System.out.println(d);
}
}
Since variable d is declared as double I am expecting the result of this program is 5.4 but I got the output as 5.0
Please help me in understanding this.
i1/i2 will be 0. Since i1 and i2 are both integers.
If you have int1/int2, if the answer is not a perfect integer, the digits after the decimal point will be removed. In your case, 2/5 is 0.4, so you'll get 0.
You can cast i1 or i2 to double (the other will be implicitly converted)
double d = 3 + (double)i1/i2 +2;
i1/i2 when converted to int gives 0. ie. why you are getting 5.0. Try this :
public static void main(String args[])
{
int i1 =2;
int i2=5;
double d = 3 + (double)i1/(double)i2 +2;
System.out.println(d);
}
This line is done in parts:
double d = 3 + i1/i2 +2;
double d = 3 + (i1/i2) +2;
double d = 3 + ((int)2/(int)3) +2;
double d = 3 + ((int)0) +2;
double d = (int)5;
double d = 5;
The double just means that the answer will be cast to a double, it doesn't have any effect till the answer is computed. You should write
double d = 3d + (double)i1/i2 +2d; //having one double in each "part" of the calculation will force it to use double maths, 3d and 2d are optional
i1/i2 will be 0 because both i1 and 12 are integers.
if you cast i1 or i2 to double then it will give the desired output.
double d = 3 + (double)i1/i2 +2;
This link provides information about data type conversion, both implicit and explicit type.
To provide exact answer to the question will be :
double d = 3 + (double)i1/i2 + 2
int i1 =2;
int i2=5;
double d = 3 + (double)i1/(double)i2 +2;
if i1/i2 will be fractional value then double will help it to be in fraction instead of int.
so now you will the result as you want. or you can also use following code
double d = 3+(double)i1/i2+2;
In this line i1 is converted into double which will be divided with i2 and result will be in double, so again result will be as 5.4
Since i1=2 and i2=5 are integer type and when you divide (2/5) them, It gives integer value (0) because fractional part(.4) get discarded.
So put (double)i1/i2 on the equation.

Categories