Division in Android Gone Wrong Value [duplicate] - java

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 1 year ago.
When I divided the large number into a small number then the division is correct but when I write the small number to divide a large number the answer returns wrong. In my scenario, the small number always be first. here is my code this code return 7.4074074074074075E-6 but the correct result is 0.0000074074.
double itf = 0.0;
double a = 4.0;
double b = 540000;
itf = a / b;
Log.i(TAG, "savedata: outputvalue=" + itf);

BigDecimal a = new BigDecimal("4");
BigDecimal b = new BigDecimal("540000");
// 0.0000074074
a.divide(b, MathContext.DECIMAL128);
You should use a decimal type. double is outside the scope of support

Related

Float and Double question confusion - Java [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 1 year ago.
double basicPay = 1999.0;
double hra = 145.0;
float experience = 3.0f;
double percentage;
if(experience<3)percentage = 0;
else if(experience>=3 && experience<5)percentage = 5;
else if(experience>=5 && experience<10)percentage = 7;
else percentage = 12;
double salary = (basicPay + hra + basicPay*(percentage/100));
System.out.println(salary);
This shows output as 2243.95
But if I change
double salary = (float)(basicPay + hra + basicPay*(percentage/100));
The answer now is 2243.949951171875
Why is this happening?
This is problem not related to Java, but to the standard of floating point numbers and their precision. Not all numbers can be represented with float. Instead of the exact value the floating point is going to get a value that is a closest approximation of the real value in floating point format. double has much more bytes to store the data, so it's more precise.
I won't go into explaining the whole thing because I believe there is plenty of resources which explain it very well, google floating point precision.

Why do I get 0.0 when I divide these two integers? [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 2 years ago.
I am trying to show the percentage of day passed using a fixed time. However, when I divide the time passed already by the total amount of time (in seconds) of a day, I get 0.0. I put the current values into the console. Any help is appreciated.
You are performing integer division, and then casting it to a double. You should be doing:
int numOfSecondsSinceMidnight = 61960;
int totalDay = 86400;
double percentDayPassed = 0;
percentDayPassed = (((double)numOfSecondsSinceMidnight / totalDay)*100);
System.out.println(percentDayPassed);
Or better yet, changing numOfSecondsSinceMidnight and totalDay to doubles:
double numOfSecondsSinceMidnight = 61960;
double totalDay = 86400;
double percentDayPassed = 0;
percentDayPassed = ((numOfSecondsSinceMidnight / totalDay)*100);
System.out.println(percentDayPassed);
Both of which print:
71.71296296296296

Wrong result when calculating floats in Eclipse [duplicate]

This question already has answers here:
Retain precision with double in Java
(24 answers)
Is floating point math broken?
(31 answers)
Closed 4 years ago.
Eclipse gives the wrong result when trying to calculate the sum of two floats.
In my code, there are 2 float variables: float from = 0.025 and float to = 1.
Then result has double variable: double value = 7 * from / to.
Eclipse compiler shows: value = 0.174999997019767760
In excel calculator, this result was value = 0.175
How can I solve this an issue?
This is simply due to your Java program not rounding the result the same way the excel calculator does. This is a result of the way computers handle floating point arithmetic. You have two options: round the result, or use the java BigDecimal class. If you want to round the result, you can use:
float from = 0.025f;
float to = 1;
double value = 7 * from / to;
DecimalFormat ds = new DecimalFormat("#.###");
double rounded = Double.parseDouble(ds.format(value));
System.out.println(rounded);
If you would rather not have to round, you can use the BigDecimal class.
Java BigDecimal

Calculate percentage with BigDecimals [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
I want to calculate the of a number I receive in BigDecimal format :
BigDecimal number1 = new BigDecimal("17");
int percentage = 50;
BigDecimal percentageAmount = number1.multiply(new BigDecimal(percentage/100));
but I got a 0 !
Cast the divided result to double. The integer division is returning zero as expected. This should work.
BigDecimal percentageAmount = number1.multiply(new BigDecimal((double)percentage/100));
Or, make the 100 to 100.0.
BigDecimal percentageAmount = number1.multiply(new BigDecimal(percentage/100.0));
These solutions would work if the number is small as you have used. But these solutions won't give the precise results when the number is big. This would be the best approach for avoiding the precision error:
BigDecimal percentageAmount = number1.multiply(BigDecimal.valueOf((double)percentage/100));

How to devide a BigInteger by a double in Java? [duplicate]

This question already has answers here:
How can I divide properly using BigDecimal
(2 answers)
Closed 5 years ago.
The title says it all: How do I divide a BigInteger by a floating point number in Java? I don’t need the fraction part of the division, it is okay to have it either rounded or truncated (however I would be interested which one applies).
The “obvious” does not even compile:
BigInteger x = BigInteger.valueOf(73).pow(42);
BigInteger y = x.divide(Math.PI); // The method divide(BigInteger) in the type BigInteger is
// not applicable for the arguments (double)
System.out.println(y);
I expected this one to work:
BigInteger y = new BigDecimal(x).divide(BigDecimal.valueOf(Math.PI)).toBigInteger();
Unluckily, it gives an ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. This is true for π, of course…
Of course, this one works, but it is way too slow…
BigInteger y = BigInteger.valueOf(-1);
BigDecimal σ = BigDecimal.ZERO;
while(σ.compareTo(new BigDecimal(x)) < 0) {
y = y.add(BigInteger.ONE);
σ = σ.add(BigDecimal.valueOf(Math.PI));
}
What’s the correct, canonical way?
You have to add RoundingMode to divide function, otherwise java doesn't know how to round the division and gives you ArithmeticException
BigInteger y = new BigDecimal(y).divide(BigDecimal.valueOf(Math.PI), RoundingMode.HALF_UP).toBigInteger();
All Rounding types are well explained in the documentation link above.

Categories