I have a simple function as defined below:
if(currentValue < smallestValue)
{
smallestValue = currentValue;
}
CurrentValue can be any value of int.
All my values are ints
What can I initialize smallestValue to so it will always be greater than the first currentValue?
By this rule: CurrentValue can be any real number, use Double.MAX_VALUE:
double smallestValue = Double.MAX_VALUE;
But the second rule negates the previous: All my values are ints, so use Integer.MAX_VALUE
int smallestValue = Integer.MAX_VALUE;
Related
I have a small doubt that I couldn't get around with that is I have a double variable which stores double value but I want it to print 0 instead of 0.0 when it has no data but whatever I try I couldn't make it work
for example:
double a = 0;
System.out.println(a);
should give me 0 instead of 0.0
I know it's a silly question but can anyone point me in the right direction,
thank you in advance.
Use some method as shown below:
double a = 0.0;
System.out.println(formatA(a));
static String formatA(double a) {
if (a == 0.0)
return "0";
else
return String.valueOf(a);
}
You can cast type of variable 'a' to an integer.
double a = 0;
System.out.println((int)a);
man, double a = 0; is a decimal type. you'd make:
change the type of the value
int a = 0
Or, also you can cast the value.
System.out.println((int) a);
If you don't want to see the fractional part of the double value, you can cast it into long value.
Note, it's not a good idea to cast it into "int" value, because max "double" value is greater than max "int" value.
double a = 0;
System.out.println((long)a);
In my PL-SQL work, I've come to regularly use the TRUNC function to check higher-position values in numeric IDs. for example:
if trunc(idValue,-3)=254000 then...
Is there a similar method available for int/Integer variables in Java?
You could take advantage of integer division here:
public int trunc(int value, int places) {
// places should be positive, not negative
int divisor = Math.pow(10, places);
int tempVal = value / divisor;
int finalVal = tempVal * divisor;
return finalVal;
}
(somewhere in your code)
if (trunc(idValue,3)==254000)
In a basic java program, I've defined two methods of a class that are supposed to return the maximum and minimum numbers from a set of four doubles. The value parameter is taken in from a for loop, and then compared to the standing min or max parameter. However, the outputs are not correct and I cannot seem to find out why; I know I have made a logic error somewhere.
The two methods-
//calculate the minimum
public double calcMin(double value, double min)
{
if (min < value)
{
min = value;
}
return value;
}
//calculate the maximum
public double calcMax(double value, double max)
{
if (max < value)
{
max = value;
}
return max;
}
The for loop-
for (int i = 0; i < fillups.length; i ++)
{
distance[i] = fillups[i].calcDistance();
milesPerGallon[i] = fillups[i].calcMPG(distance[i]);
cost[i] = fillups[i].calcTotalCost();
minimum = fillups[i].calcMin(distance[i], minimum);
maximum = fillups[i].calcMax(distance[i], maximum);
minMPG = fillups[i].calcMin(milesPerGallon[i], minMPG);
maxMPG = fillups[i].calcMax(milesPerGallon[i], maxMPG);
minPrice = fillups[i].calcMin(price[i], minPrice);
maxPrice = fillups[i].calcMax(price[i], maxPrice);
fillups[i].printResults(i, day[i], distance[i], cost[i], milesPerGallon[i]);
}
The calcMax method seems to work, but the calcMin does not. Perhaps there is a way to make them work using the Double.MAX_VALUE and Double.MIN_VALUE constants.
First, I'll repeat your two methods:
//calculate the minimum
public double calcMin(double value, double min)
{
if (min < value)
{
min = value;
}
return value;
}
//calculate the maximum
public double calcMax(double value, double max)
{
if (max < value)
{
max = value;
}
return max;
}
Do you see that you use the same logic for calcMin as you do for calcMax? Replace the < in calcMin by > and it should work.
You are searching for the smaller value thus, if the given value is smaller than the current known minimum, then you replace it.
You may start with Double.MAX_VALUE for the best known minimum at the beginning (and then you make it better every round). Analogously you may use Double.MIN_VALUE in the first round as best known maximum.
A smaller, much more compact way is to use Math.min(double, double) (and max).
Your methods themselves do some useless stuff, there is no need to assign min = value inside the method as min and value get deleted upon leaving the scope of this method. You could simply do this:
public double calcMin(double value, double min) {
if (min < value) {
return min;
} else {
return value;
}
}
For finding the smallest value in a Set you may use Collections.min(Set). But be aware that this method needs to search the whole set. It may be better using a good sorting algorithm first. Also note that a Set has no order per definition, a List is sort-able.
Well, I think you get the idea. Cheers.
Should I point out that I am a begginer at this?
double averageMonthlyTemp() {
double[] amt = new double[52];
int sum = 0;
int index = 0;
for (int i = 0; i < temp.length - 1; i = i + 7) {
//where temp is an existiing
//previously initialized array
//of 365 elements, form 0 to 364
for (int j = 0; j < 7; j++) {
sum = sum + temp[i + j];
if (j % 7 == 6) {
double average = ((double) sum) / 7;
amt[index] = average;
index++;
sum = (int) 0;
}
}
}
return amt;
}
When I try to compile, I get an "incompatible types" error, with the "amt" at return amt marked in red. Does somebody know why?
Your method averageMonthlyTemp is specified to return some value of type double, but your amt variable is actually a double[]. Either make averageMonthlyTmp return an array of doubles, or do something like this:
double averageMonthlyTmp(int month) {
...
return tmp[month]; // could be made more efficient by only calculating the temperature for one month
}
A couple of additional notes about the code:
Because j goes from 0 to 6 inclusive, the if (j % 7 == 6) can be replaced with if (j == 6). Also, it looks like that code (computing the average) can go directly after the second for loop.
In your first for loop, the code will be cleaner if you replace i = i + 7 with i += 7, which will also increase i by 7 each time.
You don't need to put (int) before the 0 in the line sum = (int) 0;, because Java knows that when you just write 0, you mean an int.
your method definition for averageMonthlyTemp says that it is supposed to return a double, that is a single value of datatype double but you are returning amt which is a double array, that is why the compiler complains. So you can either change the method definition to return an array or return a single value.
the returned value amt is double[]. But the function returns only a double value (not an array of double ). so try to rename the function as
double [] averagemonthlytemp()
{
}
Is it possible to do this?
double variable;
variable = 5;
/* the below should return true, since 5 is an int.
if variable were to equal 5.7, then it would return false. */
if(variable == int) {
//do stuff
}
I know the code probably doesn't go anything like that, but how does it go?
Or you could use the modulo operator:
(d % 1) == 0
if ((variable == Math.floor(variable)) && !Double.isInfinite(variable)) {
// integer type
}
This checks if the rounded-down value of the double is the same as the double.
Your variable could have an int or double value and Math.floor(variable) always has an int value, so if your variable is equal to Math.floor(variable) then it must have an int value.
This also doesn't work if the value of the variable is infinite or negative infinite hence adding 'as long as the variable isn't inifinite' to the condition.
Guava: DoubleMath.isMathematicalInteger. (Disclosure: I wrote it.) Or, if you aren't already importing Guava, x == Math.rint(x) is the fastest way to do it; rint is measurably faster than floor or ceil.
public static boolean isInt(double d)
{
return d == (int) d;
}
Try this way,
public static boolean isInteger(double number){
return Math.ceil(number) == Math.floor(number);
}
for example:
Math.ceil(12.9) = 13; Math.floor(12.9) = 12;
hence 12.9 is not integer, nevertheless
Math.ceil(12.0) = 12; Math.floor(12.0) =12;
hence 12.0 is integer
Here is a good solution:
if (variable == (int)variable) {
//logic
}
Consider:
Double.isFinite (value) && Double.compare (value, StrictMath.rint (value)) == 0
This sticks to core Java and avoids an equality comparison between floating point values (==) which is consdered bad. The isFinite() is necessary as rint() will pass-through infinity values.
Here's a version for Integer and Double:
private static boolean isInteger(Double variable) {
if ( variable.equals(Math.floor(variable)) &&
!Double.isInfinite(variable) &&
!Double.isNaN(variable) &&
variable <= Integer.MAX_VALUE &&
variable >= Integer.MIN_VALUE) {
return true;
} else {
return false;
}
}
To convert Double to Integer:
Integer intVariable = variable.intValue();
Similar to SkonJeet's answer above, but the performance is better (at least in java):
Double zero = 0d;
zero.longValue() == zero.doubleValue()
My simple solution:
private boolean checkIfInt(double value){
return value - Math.floor(value) == 0;
}
public static boolean isInteger(double d) {
// Note that Double.NaN is not equal to anything, even itself.
return (d == Math.floor(d)) && !Double.isInfinite(d);
}
A simple way for doing this could be
double d = 7.88; //sample example
int x=floor(d); //floor of number
int y=ceil(d); //ceil of number
if(x==y) //both floor and ceil will be same for integer number
cout<<"integer number";
else
cout<<"double number";
My solution would be
double variable=the number;
if(variable-(int)variable=0.0){
// do stuff
}
you could try in this way: get the integer value of the double, subtract this from the original double value, define a rounding range and tests if the absolute number of the new double value(without the integer part) is larger or smaller than your defined range. if it is smaller you can intend it it is an integer value. Example:
public final double testRange = 0.2;
public static boolean doubleIsInteger(double d){
int i = (int)d;
double abs = Math.abs(d-i);
return abs <= testRange;
}
If you assign to d the value 33.15 the method return true. To have better results you can assign lower values to testRange (as 0.0002) at your discretion.
Personally, I prefer the simple modulo operation solution in the accepted answer.
Unfortunately, SonarQube doesn't like equality tests with floating points without setting a round precision. So we have tried to find a more compliant solution. Here it is:
if (new BigDecimal(decimalValue).remainder(new BigDecimal(1)).equals(BigDecimal.ZERO)) {
// no decimal places
} else {
// decimal places
}
Remainder(BigDecimal) returns a BigDecimal whose value is (this % divisor). If this one's equal to zero, we know there is no floating point.
Because of % operator cannot apply to BigDecimal and int (i.e. 1) directly, so I am using the following snippet to check if the BigDecimal is an integer:
value.stripTrailingZeros().scale() <= 0
Similar (and probably inferior) to Eric Tan's answer (which checks scale):
double d = 4096.00000;
BigDecimal bd = BigDecimal.valueOf(d);
String s = bd.stripTrailingZeros().toPlainString();
boolean isInteger = s.indexOf(".")==-1;
Here's a solution:
float var = Your_Value;
if ((var - Math.floor(var)) == 0.0f)
{
// var is an integer, so do stuff
}