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.
Related
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();
}
This question already has answers here:
Fahrenheit to Celsius conversion
(3 answers)
Closed 7 years ago.
I have to divide two integers and get a float as result
My Code:
Float ws;
int i = Client.getInstance().getUser().getGespielteSpiele() -Client.getInstance().getUser().getGewonneneSpiele();
int zahl1 = Client.getInstance().getUser().getGewonneneSpiele();
ws = new Float((zahl1 / i));
I check the values with the debugger
i = 64
zahl1 = 22
ws = 0.0
Why is the result of ws 0.0? What I should do to get the correct float?
When you divide two ints you perform integer division, which, in this case will result in 22/64 = 0. Only once this is done are you creating a float. And the float representation of 0 is 0.0. If you want to perform floating point division, you should cast before dividing:
ws = ((float) zahl1) / i;
zahl1 / i is computed as int division and then converted to Float by the Float constructor. For floating point division, cast one of the operands to float or double:
ws = new Float((float)zahl1 / i);
It's because you're doing integer division,you need to change the int value as float at first.
float ws = (float) zahl1 / i;
try:
float ws = (float)zahl1/i;
How to round a decimal number to closest "whole" number?
You can try using
float x = (float)Math.ceil(x);
or
float y = (float)Math.round(y);
Also note that I have converted them back to float as there may be a loss of precision when you are converting double to float.
One line answer!
public static long roundToClosestLong(long num, long div) {
return (long) num / div + ((double) (num % div) / div < 0.5 ? 0 : 1);
}
You can use java.lang.Math class for that.
Math#round(double) Will accecpt double as argument and returns long
Math#round(float) Will accecpt float as argument and returns int
You could do:
int result = (int) (yourValue + 0.5);
if you just need simple rounding this is maybe a more performant solution than Math.round(yourValue)
I am trying to add together several large numbers to make a weighted fraction. If there are three numbers going into the fraction(a, b, c), the weighted fraction should be : (1/a)/((1/a)+(1/b)+(1/c))
For now I am only trying to correct the denominator portion of the fraction. The sorted array is
{{15 9 13},{15 18 16},{9 18 12},{13 12 16},{17 24 25}}
I am trying to use a big decimal since double and float don't seem to capture the very small fraction that results from weighting. However even with the big decimal, the print out is still 0. What am I doing wrong?
public static BigDecimal[][] weights(int[][]sorted, int k){
BigDecimal [][] weighted = new BigDecimal[sorted.length][k]; //k=3
BigDecimal denom = BigDecimal.ZERO;
for (int i = 0; i<sorted.length; i++){ //sums to create denominator value
for(int j = 0; j<sorted[i].length; j++){
denom = denom.add(new BigDecimal(1/sorted[i][j]));
System.out.println("denom " + denom);
}
}
return weighted;
}
Any help would be greatly appreciated!!
Even with BigDecimals, you are still performing integer division before the value even goes into the BigDecimal, with 1/sorted[i][j]. Integer division in Java must result in another int, so 1 divided by any positive int 2 or greater will result in 0.
Use the double literal 1.0 to force floating-point arithmetic.
1.0 / sorted[i][j]
Then you'll find that BigDecimal is unnecessary and a double denom will work well.
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.