It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
What do you think Float.MIN_VALUE equals to?
The next code explains where my last 5 hours went to, trying solving a bug.
public static void main(String[] args) {
compareToZero(Float.MIN_VALUE); // Out = true false false
compareToZero(Float.MAX_VALUE); // Out = true false false
System.out.println("Float minimum " + Float.MIN_VALUE); // Out = 1.4E-45
System.out.println("Float maximum " + Float.MAX_VALUE); // Out = 3.4028235E38
}
private static void compareToZero(float value1) {
System.out.print((value1 > 0) + " ");
System.out.print((value1 < 0) + " ");
System.out.print((value1 == 0) + "\n");
}
I didn't imagined that minimum value of float will be a positive value... Can't find any use for it.
Per the documentation for Float.MIN_VALUE:
A constant holding the smallest positive nonzero value of type float, 2-149. It is equal to the hexadecimal floating-point literal 0x0.000002P-126f and also equal to Float.intBitsToFloat(0x1).
While the name is debatable as the "true minimum value" of a float is -Float.MAX_VALUE, I suspect MIN_VALUE was chosen for consistency with the other numeric types. Using the names MIN_RANGE_VALUE and MAX_RANGE_VALUE (or similar) might have made the difference more clear.
To understand why this is the "minimum value" requires understanding a little bit about how Java (or IEEE-754) floating point values work. With this insight, after reading the documentation, it is clear that Float.MIN_VALUE is the minimum non-zero value representable by the mantissa and exponent components of a float. Or, the smallest positive value a float can represent.
The "true minimum value" is -Float.MAX_VALUE because Float.MAX_VALUE represents the maximum value that the mantissa and exponent components of a float can represent. Since the sign for a float is stored as a discrete bit, this range limit is the same for both positive and negative numbers.
This differs from how integers work in Java (and on most CPUs): they are encoded using two's complement. (Some computer systems used a discrete sign bit, which is called "one's complement", which then has two integer values of zero: 0 and -0!)
Happy researching!
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 months ago.
Improve this question
I'm trying to read the following value from an Excel file cell:
19,000,000.00
19,000,000.10
19,000,000.01
19,000,000.101
What I see in the Excel file are also those values.
However, my output respectively, when using cell.getNumericValue():
1.9E+7
19,000,000.1
19,000,000.01
19,000,000.101
The conversion to the exponential values makes it hard to manipulate and obtain all the information I need from the value, because when calling the .scale() and .precision() methods, the value is completely off. (the exponential value in question gives me precision: 2; scale: -6 )
How do I make it so that I get what I see instead of the conversion? My end-goal, basically, is to ensure the length of the value does not exceed my settings (eg. Numeric(15, 3) )
I've tried:
Double.parseDouble()
BigDecimal.valueOf().doubleValue()
BigDecimal.valueOf().floatValue()
But everything keeps returning me back the exponential value.
Edit
Due to request, portion of the code I'm doing, modified as to not show the whole thing and clutter:
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
Object theObject = new Object();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext() && !hasError) {
Cell cell = cellIterator.next();
theColumnIndex = cell.getColumnIndex();
(switch statement omitted)
numericValue = cell.getNumericCellValue();
//numericValue will return values like 1.9E+7, 19000000.10
// 19000000.01, 19000000.101
// afaik, the return type is Double
theObject.setAmount( BigDecimal.valueOf(numericValue) );
//SetAmount function expects a BigDecimal input, hence the use
/*
Additional checking for length and precision here to try and catch and
log it. Put after and not before because so long as it's a valid value (ie.
not String), it should still go in.
*/
}
You should avoid the BigDecimal constructor with a double as floating point has no precision (scale). From a String the BigDecimal can determine the precision (scale -2 below).
BigDecimal n = new BigDecimal("19000000.00");
So one should not get double values from Excel.
Then for text presentation without scientific exponent notation:
System.out.println(n.toPlainString());
As already commented, you should not do numerical constraint checks based on a text representation of a number.
If I remember correctly Numberic(15,3) basically means "15 digits, 3 of which are decimal places". This means you'd have the following constraints:
min value: -999,999,999,999.999
max value: 999,999,999,999.999
max 3 decimal places
To check this you could do the following:
//construct the boundary values once and cache them
BigDecimal max = new BigDecimal("999999999999.999");
BigDecimal min = max.negate();
//get the value and strip trailing zeros to get `x.01` instead of `x.01000` etc.
BigDecimal value = cell.getNumericValue().stripTrailingZeros();
//check validity
boolean valid = min.compareTo(value) < 0 && //value not smaller than min which would mean more digits
max.compareTo(value) > 0 && //value not larger than max which would mean more digits
value.scale() <= 3; //scale <= 3, i.e. 3 decimal digits at most
Note on scale(): a negative value basically defines the number of zeros that would be added to the internally stored unscaled integer value, e.g. value = 123 and scale = -5 would actually mean "123 + 5 zeros, i.e. 12,300,000". A negative scale thus also implies that there are no fraction digits while a positive scale would indicate the number of fraction digits ("value = 123 and scale 2" would mean "move the decimal point 2 places to the left" so the actual value would be 1.23 - which means 2 fraction digits).
This question already has answers here:
Why I am getting -2147483648 and -1's multiplication, negative i.e. -2147483648, instead it should be +2147483648 [duplicate]
(1 answer)
How does Java handle integer underflows and overflows and how would you check for it?
(12 answers)
How are integers internally represented at a bit level in Java?
(10 answers)
Why does the negative of Integer.MIN_VALUE give the same value? [duplicate]
(2 answers)
Closed 2 years ago.
I’m recently facing the below problem
public class Main {
public static void main(String[] args) throws Exception {
// Your code here!
int i = -2147483648;
int j = i * -1;
System.out.println("j="+j);
}
}
Result : -2147483648
Online IDE with code :
https://paiza.io/projects/e/17lF_6-GltIcyubZv3QoFg?theme=twilight
But how it’s works as per the logic I need to get 2147483648 is a result right?
Then how I got this negative number ?
It’s because of integer range (Integer.MIN_VALUE)?
how to fix this issue?
The maximum postive value an int can hold is 2147483647 beyond which the value goes to the other end (i.e. it starts from the negative end). You can understand it from the following demo:
public class Main {
public static void main(String[] args) {
int i = -2147483648;
int j = i * -1;
System.out.println("j=" + j);
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MAX_VALUE + 1);
System.out.println(Integer.MIN_VALUE);
// Some more examples for you to understand this concept better
System.out.println(Integer.MAX_VALUE + 2);
System.out.println(Integer.MAX_VALUE + 3);
}
}
Output:
j=-2147483648
2147483647
-2147483648
-2147483648
-2147483647
-2147483646
After -2147483648 is multipled with -1, it becomes 2147483648 but an int variable can not hold this much big positive value; so, it will start from the negative end (i.e. Integer.MIN_VALUE).
The number 2147483648 does not exists. The biggest value of an int is 2147483647, which is 1 smaller than your expected result. The multiplication causes an overflow, which 'rolls back' the number to the smallest negative value, and continues the calculation from there. (With other words: 2147483647+1=-2147483648 (smallest negative)) Since the result would only be 1 over the maximum value, there is no additional action required and the minimal int value is returned.
If you want to fix this issue, use 'long' instead of 'int' for your variables. You can also use more complex classes like BigDecimal, or write a custom multiplication function for byte arrays.
Note: no matter what numeric type you use, as long as the memory used for representing the number is finite you can run into similar issues. Although under normal circumstances it is unlikely, even for a 32-bit integer (int).
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I was just wondering if there was an alternative to the following operator:
if (f == 0){
System.out.print("");
} else if (i %2 == 1){
System.out.print("; ");
}
To be clearer, I would like an alternative way of writing the if statement's "==" and the else if statement's %2 == 1.
Thanks.
System.out.print(f!=0 && i%2==1 ? "; " : "");
Instead of the modulo you can flag out all bits of i except the last one by a bitwise and.
The alternative to i%2 is i&1.
In java 7 you can compare like this
int result = Integer.compare(f, 10);
Description of the method
public static int compare(int x,
int y)
Compares two int values numerically. The value returned is identical to what would be returned by:
Integer.valueOf(x).compareTo(Integer.valueOf(y))
Parameters:
x - the first int to compare
y - the second int to compare
Returns:
the value 0 if x == y; a value less than 0 if x < y; and a value greater than 0 if x > y
Since: 1.7
Taken from official document
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#compare%28int,%20int%29
and In java 6
int result = Double.compare(f, 10);
Description of the method
compare
public static int compare(double d1,
double d2)
Compares the two specified double values. The sign of the integer value returned is the same as that of the integer that would be returned by the call:
new Double(d1).compareTo(new Double(d2))
Parameters:
d1 - the first double to compare
d2 - the second double to compare
Returns:
the value 0 if d1 is numerically equal to d2; a value less than 0 if d1 is numerically less than d2; and a value greater than 0 if d1 is numerically greater than d2.
Since:
1.4
Taken fropm official docs
http://docs.oracle.com/javase/6/docs/api/java/lang/Double.html#compare%28double,%20double%29
you can use any of the approach according to your requirements
I have tested both of them
see my tested solution
for java 6 http://ideone.com/56dm1T
for java 7 http://ideone.com/mEjt6W
Equals operator == compares references in the case of objects and actual values in the case of primitive types.
A scenario where this operator can be replaced with equals(Object obj) is when the wrapper objects of primitive types are used.
So, if there are two int, a and b, and you obtain their wrappers with:
Integer objA = Integer.valueOf(a);
Integer objB = Integer.valueOf(b);
a == b gives the same result as objA.equals(objB).
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I need to print the first k digits and the last k digits in
n^n (n to the power of n, where n is an integer)
For example :
Input Output
n k First k digits Last k digits
4 2 --> 25 56
9 3 --> 387 489
I sense that it requires some clever mathematics, however I am unable to think of anything as such. Please suggest a way to approach the problem.
The last k digits are easy, you just need to calculate it modulo 10^k. To do this, after every multiplication, just apply the modulo, ie. intermediate_result %= 10^k.
Of course, you will need to calculate 10^k using some other method, because ^ does not mean power of in C or Java.
To find the first k digits, see first n digits of an exponentiation.
Thanks everyone for their help. My final code is
#include <stdio.h>
#include <math.h>
long int lastKdigits(long long n,int k)
{
long long i,res=1,div=pow(10,k);
for(i=1;i<=n;i++)
{
res=(res*n)%div;
}
return res;
}
long int firstKdigits(long long n,int k)
{
long double x, y;
x = n*log10(n);
y = floor(pow(10,x-floor(x) +k-1));
return ((int)y);
}
int main()
{
long long n;
int k;
scanf("%lld %d",&n,&k);
printf("%ld\t",firstKdigits(n,k));
printf("%ld\n",lastKdigits(n,k));
}
return 0;
}
For last k digits it's pretty easy you just need to calculate n^n (mod 10^k) but I don't know any solution for the other k diggits!
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
public void mystery1(int n) {
if (n <= 1) {
System.out.print(n);
} else {
mystery1(n / 2);
System.out.print(", " + n);
}
}
What gives this code for odd numbers. Becuase when we divide it it will not be an integer.
There is not mystery, because result of the integer division in Java is integer.
In Java or most other programming languages, when you divide an integer by an integer, the result will be an integer. If a decimal number occurs, say for example:
5/2=2.5
then, the number before the decimal point will be treated as the integer and 2 will be chosen.
In case you want to explicitly convert the integer into float or double, you can use any of the following conversions:
(float) 3/2;
(double) n/2;
The above explicitly converts it to a decimal.
n / 2, this is an integer division, where the fraction part will be ignored.
System.out.println(3/2); // prints 1
System.out.println(3.0/2); // prints 1.5
System.out.println(3/2.0); // prints 1.5
System.out.println(3.0/2.0); // prints 1.5
Param will rounded to int, for example if param will be 5, the next call the function will be with param 2