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();
}
Related
Recently this question asked in Java interview. Tried and searched the solution but can't find. kindly, comment the solution if anybody knows. It would be helpful.
Zeroes in the numeric basic types. Float and double have two zeroes each. That's nine values. Then there's MIN_VALUE for int and long. That's eleven.
So:
int x = 0;
int x = Integer.MIN_VALUE;
long x = 0;
long x = Long.MIN_VALUE;
byte x = 0;
short x = 0;
char x = 0;
double x = 0.0;
double x = -0.0;
float x = 0f;
float x = -0f;
Then each of those values wrapped as an object:
Integer x = 0;
Integer x = Integer.MIN_VALUE;
Long x = 0L;
Long x = Long.MIN_VALUE;
Byte x = 0;
Short x = 0;
Character x = 0;
Double x = 0.0;
Double x = -0.0;
Float x = 0f;
Float x = -0f;
That's 22 total.
(I wouldn't have called the objects more values. They're the same 11 values again but wrapped in objects. But if you're supposed to find 22 total, I think this must be it.)
Note that for smaller integral types, like short, performing -x would widen them to an int, so x==-x does not work for Short.MIN_VALUE.
x==-x evaluates as true for floating-point zeroes, because even though positive zero and negative zero are different values, they are regarded as equal to each other.
Why this is not allowed?
float n;
n = 1234567.89;
but this is.
float n;
n = (float) 12.3456789;
I'm using JAVA 8 and Netbeans 8.0.1.
IDE snapshot below.
By default, Java interprets literal decimals as double, so to enter a float you need to do one of the following:
float n = 1234567.89f;
float n = (float) 1234567.89;
Note that doing so may result in a loss of precision.
java treat it as double in first line. n = 1234567.89 not as float. double is 8 byte and float is 4 byte.
solution is
float n;
n = 1234567.89f;
Use
float n;
n = 1234567.89f;
This declares your number as being a float value instead of a double value by default.
When you define a decimal number as 1234567.89, its interpreted as a double.
Float numbers end with a letter f. You can define it as below.
float n;
n = 1234567.89f;
Float is a 32 bit IEEE 754 floating point. Double is a 64 bit IEEE 754 floating point.
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
I came across the following silly function here:
public static String findOutWhatLifeIsAllAbout() {
int meaning = 0;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 20; j++) {
for (int k = 0; k < 300; k++) {
for (int m = 0; m < 7000; m++) {
meaning += Math.random() + 1;
}
}
}
}
return String.valueOf(meaning).replaceAll("0*$", "");
}
In summary, the expected result is a string "42", since Math.random() returns doubles "greater than or equal to 0.0 and less than 1.0". In practice, running on an i5 under Ubuntu the resulting strings are similar to "420000011", "420000008"! (meaning sometimes Math.random()'s result is getting rounded up!
To get a grip on what sorts of double values would cause Math.random()'s result to somehow round to 1, I tried this function instead, expecting to see some examples.
public static String findOutWhatLifeIsAllAboutAltered() {
int meaning = 0;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 20; j++) {
for (int k = 0; k < 300; k++) {
for (int m = 0; m < 7000; m++) {
double randomResult = Math.random();
int converted = randomResult;
if (converted > 0) {
System.out.println("Misbehaving double = " + randomResult);
}
meaning += converted + 1;
}
}
}
}
return String.valueOf(meaning).replaceAll("0*$", "");
}
However this formulation always returns "42"! Can anyone offer insight about why the behavior changes in the altered function? Thanks.
Furthermore why does Java let the original function compile at all? Shouldn't there be a loss-of-precision error at the += call?
edit posted the code I wanted you all to see - the "original" version wasn't supposed to have a cast.
There's a small but important difference between the code in the link and the code originally posted here,
meaning += Math.random() + 1; // link
vs.
meaning += (int)Math.random() + 1; // StackOverflow
If the code posted here prints out anything but 42, it's a serious bug.
Here, the result of Math.random() is explicitly cast to int, that must result in 0, then 1 is added, resulting in 1, which then is added to meaning.
The code in the linked post, however performs an implicit cast to int after adding the result of Math.random() to 1 and that to meaning, basically
meaning = (int)(Math.random() + (double)1 + (double)meaning);
Now, if the result of Math.random() is close enough to 1.0, it occasionally happens that the result of the double addition is rounded up, so producing a final result slightly larger than immediately expected.
Shouldn't there be a loss-of-precision error at the += call?
No. In the first case, you're explicitly casting the value returned by Math.random() to an int. In the second case, meaning, converted, and 1 are all integers.
There is, however, a possible loss-of-precision at this line:
int converted = randomResult;
http://ideone.com/1ZTDi
There won't be a loss of precision error at all because they're all ints in this example - you're not actually adding any doubles!
The only line where you could be you're casting the result of Math.random() to an int - so you're still just adding two ints together.
However, even if you were adding doubles to an int then there still wouldn't be because the JLS defines an implicit cast for these types of operators:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
Source:
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.26.2
Loss of precision could only come on these lines as you're doing type conversion:
double randomResult = Math.random();
int converted = randomResult;
As Math.random() returns an double which is between 0.0 inclusive and 1.0 exclusive, the variable converted will only ever contain 0 as it's converted to an int.
For more on the casting from a double > int, see here: Different answer when converting a Double to an Int - Java vs .Net
I've tried your original program on a Java 6 system running on Mac OS X (Lion) and it only outputs 42. Which JRE/JDK are you using?
I have an Integer value been passed in and then it is divided by 100, so result could either be an int or double so not sure if cast it or not.
public void setWavelength(Integer value) {
this.wavelength = value;
}
then value divided by 100
pluggable.setWavelength(entry.getPluggableInvWavelength()/100);
So not sure how to cast this value/object
If you divide an integer (int) by an other integer (int) the result will be an integer (int) again.
-- More details: 15.17 Multiplicative Operators
You need to mark one or both as double
//cast the divisor entry.getPluggableInvWavelength() to double
pluggable.setWavelength( ((double) entry.getPluggableInvWavelength()) /100);
or
//make the constant quotient a double
pluggable.setWavelength(entry.getPluggableInvWavelength() /100.0);
Pay attention to the fact, that java.lang.Integer is a immutable wrapper type and not an int! - In fact you can not calculate with java.lang.Integer, but since Java 1.5 the compiler will convert int to Integer and back automatically (auto boxing and auto unboxing). But in general it is better to understand the difference and use Integer only if you real need objects (and not numbers to calculate).
If waveLength is double, then have:
entry.getPluggableWavelength() / 100d;
d means that the number is treated as double, and hence the division result is double.
If you divide an int by an int, you always get an int. If you want a float or a double (because you need to represent fractional parts of the result), then you'll need to cast one or both inputs:
int a = 3;
int b = 4;
int c1 = a / b; // Equals 0
double c2 = a / b; // Still equals 0
double c3 = (double)a / (double)b; // Equals 0.75
if entry.getPluggableInvWavelength() returnsd an int the results of /100 will also be an int
If you have to have a double result, then you must store a double result.
double wavelength;
public void setWavelength(double value) {
this.wavelength = value;
}
pluggable.setWavelength(entry.getPluggableInvWavelength()/100.0);
Dividing by 100.0 is all you need to have a double result with 2 decimal places.