Reputation: 315
So I have two Integers, I am finding their median by adding them and then dividing them by 2. I want to store their floating result. So I am doing -
float res = (float) (num1 + num2) / 2;
Sometimes this expression return 0.0 for non zero inputs. I think the problem is num1 and and num2 range can vary to the full spectrum of 32 bits. So when both are in the high spectrum, float cast breaks as its not able to store the results and returns 0.0.
I don't want to do (float)num1/2 + (float)num2/2
as I might loose decimal precision during this.
Any pointers on how can I handle this scenario.
Upvotes: 0
Views: 252
Reputation: 696
Use BigDecimal type for this purpose.
int num1 = 1;
int num2 = 2;
BigDecimal sum = new BigDecimal(num1 + num2);
BigDecimal result = sum.divide(new BigDecimal(2));
In case num1
and num2
are the floating-point types, use
BigDecimal sum = new BigDecimal(num1).add(new BigDecimal(num2));
Then you can get any type from result, for example
double v = result.doubleValue();
Upvotes: 1
Reputation: 14062
I did a simple test, and as I mentioned in my comment, you can cast it with double
or long
(as another option):
public class Casting {
public static void main(String[] args) {
// the maximum positive value for a signed binary integer
int num1 = Integer.MAX_VALUE;
int num2 = Integer.MAX_VALUE;
float resFloat = ((float)num1 + num2) / 2;
double resDouble = ((double)num1 + num2) / 2;
double resLong = ((long)num1 + num2) / 2;
// Testing [Expected Result is 2147483647]
System.out.println("Size: " + Integer.SIZE); // in bits (on my machine)
System.out.println("Max Value: " + Integer.MAX_VALUE);
System.out.printf("Float Cast: %f\n", resFloat);
System.out.printf("Double Cast: %f\n", resDouble);
System.out.printf("Long Cast: %f\n", resLong);
}
}
Output
Size: 32
Max Value: 2147483647
Float Cast: 2147483648.000000
Double Cast: 2147483647.000000
Long Cast: 2147483647.000000
Upvotes: 0
Reputation: 20059
Depending what your actual requirements are, float may not do the trick either.
For a correct result try this:
int num 1 = ...
int num 2 = ...
double avg = (((long) num1) + num2) / 2D;
The point is to add the int's as long's (cast one to long, the other is cast automatically because long + int causes a widening conversion). This avoids a possible integer overflow when the sum of both ints is larger than Integer.MAX_VALUE (or smaller than Integer.MIN_VALUE).
Then divide by two, by suffixing the 2 literal as double literal an explicit cast is not needed. Again for the division this causes an implicit widening conversion where long / double = double.
Upvotes: 5