How can I get the correct answer when I need to use BigDecimal without losing precision.
BigDecimal a = new BigDecimal(0.5);
BigDecimal b = new BigDecimal(30);
BigDecimal c = new BigDecimal(18000);
a.divide(b).multiply(c);
How could I get the exact 300 in this case?
Thanks!
You can use the MathContext parameter in the divide method for this.
For example, a.divide(b, MathContext.DECIMAL128).multiply(c); will give you the precision you need (with an error of magnitude 1e-32). If you do not want to lose any precision, you can use MathContext.UNLIMITED, but this will result in a non-terminating decimal expansion.
In your case specifically, you can also try to rewrite the equation to prevent any rounding from happening: a / b * c = c / b * a.
Related
I want to perform a ceiling function on a number (33.1504352455) so that it returns 33.16. When using ceiling, of course, it returns 34.0. How would I shift the character that the ceiling is acting on so that it returns 33.16?
For better precision, always opt for BigDecimal. You could do it like:
BigDecimal b = new BigDecimal(33.1504352455);
b = b.setScale(2, RoundingMode.CEILING)
System.out.println(b);
You could try
number = Math.ceil(oldnumber * 100) / 100.0;
But this could be subject to the vagaries of floating point math.
I want to substract 2 double values, and I have tried the following code.
double val1 = 2.0;
double val2 = 1.10;
System.out.println(val1 - val2);
and I got the output as,
0.8999999999999999
For getting output as 0.9 I tried with BigDecimal as follows,
BigDecimal val1BD = new BigDecimal(val1);
BigDecimal val2BD = new BigDecimal(val2);
System.out.println(val1BD.subtract(val2BD));
And I got the output as,
0.899999999999999911182158029987476766109466552734375
Then I tried with BigDecimal.valueOf()
val1BD = BigDecimal.valueOf(val1);
val2BD = BigDecimal.valueOf(val2);
System.out.println(val1BD.subtract(val2BD));
And finally I got the output as 0.9.
My question is what is the difference between case 2 & case 3?
In case 2 why I got the output like that?
BigDecimal.valueOf(double d) uses canonical String representation of double value, internally Double.toString(double) is used, that's why you are getting 0.9 in second case.
Note: This is generally the preferred way to convert a double (or
float) into a BigDecimal, as the value returned is equal to that
resulting from constructing a BigDecimal from the result of using
Double.toString(double).
While with new BigDecimal(0.9) it converts value to exact floating point representation of double value without using String representation,
Translates a double into a BigDecimal which is the exact decimal
representation of the double's binary floating-point value.
...
NOTES :
The results of this constructor can be somewhat unpredictable.
...
FOR EXAMPLE :
BigDecimal bd1 = new BigDecimal(Double.toString(0.9));
BigDecimal bd2 = new BigDecimal(0.9);
System.out.println(bd1);
System.out.println(bd2);
OUTPUT :
0.9
0.90000000000000002220446049250313080847263336181640625
Just for those others that got here looking for some other issue with BigDecimal(not related to the question above)...
remember to give a mathContext to the methods to avoid certain problems e.g.
MathContext mc = new MathContext(10, RoundingMode.HALF_UP);
BigDecimal hitRate = new BigDecimal(totalGetValuesHitted).divide(new BigDecimal(totalGetValuesRequested), mc);
BigDecimal missRate = new BigDecimal(1.0, mc).subtract(hitRate, mc);
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 7 years ago.
double x = 0.00090;
double b = 0.00100;
double c = x - b;
produces
-1.0000000000000005E-4
instead of
-0.0001
and
double x = -0.09;
double b = 0.001;
double c = x * b;
produces
-8.999999999999999E-5
instead of
-0.00009
I also tried with
Math.round(c) and Math.round(c*100.0)/100.0
but it is producing same results or results with incomplete number range after decimal.
That's how numeric operations are defined in the specification.
Decimal numbers are internally represented as the closest approximation, which in some cases is not the exact literal value.
If you need precise numeric computation, you have to use BigDecimal.
The answers are correct. You might want to read up on how doubles are stored in binary digits. its because it's base 2. If we used something like base 3, then in normal digits, 2/3 would be 0.66666666... but in the "tridigit" it would be 0.2
The E notation is confusing you (explanation on how it works here)
-1.0000000000000005E-4
is
-0.00010000000000000005
in standard notation and
-8.999999999999999E-5
is
-0.00008999999999999999
in standard notation. All the answer you see are correct (almost, but they are very close, decimal math isn't always precise), just using the E notation.
try this:
double x = 0.00090;
double b = 0.00100;
BigDecimal xd = new BigDecimal(x).setScale(10, RoundingMode.HALF_UP);
BigDecimal bd = new BigDecimal(b).setScale(10, RoundingMode.HALF_UP);
BigDecimal cd = xd.multiply(bd);
double c = cd.doubleValue();
System.out.println(c);
For precise calculations, like money calculations, you should use BigDecimals, because they have desired precision, and don't lost any accuracy.
If you prefer printing without "E", try this line:
System.out.println(cd.toPlainString());
I have got a Problem, I am developing an Application which should be able to do some mathematic calculations. These calculations have to be exact (or rather not obviously wrong)
But this simple Code
double a = 3.048d;
double b = 1000d;
double c = a / b;
gives me a wrong result c is not 0.003048 as expected instead it is 0.0030480000000000004 which is obviously wrong.
double d = 3.048 / 1000;
this second code-snipet gives the correct result.
I am aware that all floatingpoint arithmetic is not exact when calculating with computers but I don't know how to solve this problem.
thanks in advance!
Ludwig
Developing for:
- Android 2.2
Testdevice:
- HTC Desire
What you need to use for exact percision is the BigDecimal object:
BigDecimal a = new BigDecimal("3.048");
BigDecimal b = new BigDecimal(1000);
BigDecimal c = a.divide(b);
System.out.println(c); //0.003048
This is a consequence of the IEEE 754 floating point representation, not an error. To deal with it, round your result to an appropriate precision.
Use a BigDecimal for precise floating point calculations. Setting the scale allows you to specify precisely how far out you want to go for output.
import java.math.BigDecimal;
class Test{
public static void main(String[] args){
BigDecimal a = new BigDecimal("3.048");
BigDecimal b = new BigDecimal(1000);
BigDecimal c = a.divide(b).setScale(6);
System.out.println(c); //0.003048
}
}
Use BigDecimal for such precise allocations.
Btw the result for d is obviously right, because double has a machine encoding which cannot store the result, which you perceive as correct.
Why does the following code raise the exception shown below?
BigDecimal a = new BigDecimal("1.6");
BigDecimal b = new BigDecimal("9.2");
a.divide(b) // results in the following exception.
Exception:
java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
From the Java 11 BigDecimal docs:
When a MathContext object is supplied with a precision setting of 0 (for example, MathContext.UNLIMITED), arithmetic operations are exact, as are the arithmetic methods which take no MathContext object. (This is the only behavior that was supported in releases prior to 5.)
As a corollary of computing the exact result, the rounding mode setting of a MathContext object with a precision setting of 0 is not used and thus irrelevant. In the case of divide, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3.
If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an ArithmeticException is thrown. Otherwise, the exact result of the division is returned, as done for other operations.
To fix, you need to do something like this:
a.divide(b, 2, RoundingMode.HALF_UP)
where 2 is the scale and RoundingMode.HALF_UP is rounding mode
For more details see this blog post.
Because you're not specifying a precision and a rounding-mode. BigDecimal is complaining that it could use 10, 20, 5000, or infinity decimal places, and it still wouldn't be able to give you an exact representation of the number. So instead of giving you an incorrect BigDecimal, it just whinges at you.
However, if you supply a RoundingMode and a precision, then it will be able to convert (eg. 1.333333333-to-infinity to something like 1.3333 ... but you as the programmer need to tell it what precision you're 'happy with'.
You can do
a.divide(b, MathContext.DECIMAL128)
You can choose the number of bits you want: either 32, 64 or 128.
Check out this link :
http://edelstein.pebbles.cs.cmu.edu/jadeite/main.php?api=java6&state=class&package=java.math&class=MathContext
To fix such an issue I have used the below code
a.divide(b, 2, RoundingMode.HALF_EVEN)
Where 2 is scale. Now the problem should be resolved.
I had this same problem, because my line of code was:
txtTotalInvoice.setText(var1.divide(var2).doubleValue() + "");
I change to this, reading previous Answer, because I was not writing decimal precision:
txtTotalInvoice.setText(var1.divide(var2,4, RoundingMode.HALF_UP).doubleValue() + "");
4 is Decimal Precison
AND RoundingMode are Enum constants, you could choose any of this
UP, DOWN, CEILING, FLOOR, HALF_DOWN, HALF_EVEN, HALF_UP
In this Case HALF_UP, will have this result:
2.4 = 2
2.5 = 3
2.7 = 3
You can check the RoundingMode information here: http://www.javabeat.net/precise-rounding-of-decimals-using-rounding-mode-enumeration/
It´s a issue of rounding the result, the solution for me is the following.
divider.divide(dividend,RoundingMode.HALF_UP);
Answer for BigDecimal throws ArithmeticException
public static void main(String[] args) {
int age = 30;
BigDecimal retireMentFund = new BigDecimal("10000.00");
retireMentFund.setScale(2,BigDecimal.ROUND_HALF_UP);
BigDecimal yearsInRetirement = new BigDecimal("20.00");
String name = " Dennis";
for ( int i = age; i <=65; i++){
recalculate(retireMentFund,new BigDecimal("0.10"));
}
BigDecimal monthlyPension = retireMentFund.divide(
yearsInRetirement.divide(new BigDecimal("12"), new MathContext(2, RoundingMode.CEILING)), new MathContext(2, RoundingMode.CEILING));
System.out.println(name+ " will have £" + monthlyPension +" per month for retirement");
}
public static void recalculate (BigDecimal fundAmount, BigDecimal rate){
fundAmount.multiply(rate.add(new BigDecimal("1.00")));
}
Add MathContext object in your divide method call and adjust precision and rounding mode. This should fix your problem
Your program does not know what precision for decimal numbers to use so it throws:
java.lang.ArithmeticException: Non-terminating decimal expansion
Solution to bypass exception:
MathContext precision = new MathContext(int setPrecisionYouWant); // example 2
BigDecimal a = new BigDecimal("1.6",precision);
BigDecimal b = new BigDecimal("9.2",precision);
a.divide(b) // result = 0.17
For me, it's working with this:
BigDecimal a = new BigDecimal("9999999999.6666",precision);
BigDecimal b = new BigDecimal("21",precision);
a.divideToIntegralValue(b).setScale(2)