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

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.

Related

Division in Android Gone Wrong Value [duplicate]

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

Android Studio not calculating float value...or am I dumb? [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
int totalOptCount = 500;
int totalRespCount=1500;
float percentage =(float)(totalOptCount/totalRespCount);
Why does this always return value 0.0? Also I want to format this into 00.00 format and convert into string?
Because the conversion to float happens after the division has been done. You need:
float percentage = ((float) totalOptCount) / totalRespCount;
You should be able to format using something like:
String str = String.format("%2.02f", percentage);
If you are using int values, using a double may be a better choice and have less rounding error. float can represent int values without error up to ~16 million. double can accurately represent all int values.
double percentage =(double) totalOptCount / totalRespCount;
Percentages are usually multiplied by 100, meaning you can drop the cast.
double percentage = 100.0 * totalOptCount / totalRespCount;
(totalOptCount/totalRespCount)
here both dividend and divisor are of type int which means they will allow only integer values and the answer of such equation will always be an integer literal.
if I break this it will be something like below
(double)(500/1500)
According to the actual calculation, 500/1500 will give you 0.33333 but compiler will convert this into integer literal because both operands are of type int
(double)(0)
Compiler gets an instruction to cast this 0 value to double so you got 0.0 as result
0.0
and then you can change the result to any format as suggeted by #Zach Janicki.
keep in mind if both the operands are of same type than result will be of same type too.
Integer division (which includes long, short, byte, char, int) in Java always returns an int (or long, if one of the parameters is long), rounding towards zero. Your conversion occurs after this calculation.
(The formatting question is already answered by the other answers - alternatively you could also have a look at java.text.NumberFormat, specially java.text.DecimalFormat.)
String.format("%2.02f", (float)totalOptCount/totalRespCount);
to format a double and print out as a percentage, you can use use
System.out.println(new DecimalFormat("##.##").format(yourDouble) + "%"));

Trouble evaluating decimal values in java [duplicate]

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());

multiply Bigdecimal and int generating error [duplicate]

This question already has answers here:
How to multiply a BigDecimal by an integer in Java
(3 answers)
Closed 8 years ago.
I have one value like 0.0004 when I store this in Integer it is converting into Exponential format, So I have used Bigdecimal to convert it to normal value like below
Bigdecimal x=BigDecimal.valueOf(0.0004)
Now I am trying to multiply as x*100 but I am getting below error.
Error: The operator * is undefined for the argument type(s) BigDecimal, int
Because of this error if I use this without bigdecimal again it is converting to EXponential.
Can any one please suggest me the way to multiply Bigdecimal and int.
googled a lot but couldn't find the correct solution.
Thanks for your time
You can use BigDecimal.multiply to multiply your BigDecimal.
However, the int value of 0.0004 * 100 will be 0, which is probably not what you want.
Finally, you can alter the how the BigDecimal is represented in terms of fractional digits by using a NumberFormat instance and formatting your Number.
Here's an example:
BigDecimal x= BigDecimal.valueOf(0.0004);
BigDecimal y = x.multiply(new BigDecimal("100"));
int z = y.intValue();
System.out.printf("y is %s\tz is %d%n", y, z);
// edit to truncate fractional digits
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
System.out.printf("y (2 fraction digits) is %s", nf.format(y));
Output
y is 0.04000 z is 0
y (2 fraction digits) is 0.04
BigDecimal's are objects. They don't have normal operators.
Instead of a normal multiplication operator like x*10, you need to call the method multiply in BigDecimal:
x = x.multiply(new BigDecimal(10));
If you want to store it in a new value:
BigDecimal n = x.multiply(new BigDecimal(10));
And to convert that to a primative:
double d = n.doubleValue();
int i = n.intValue();
However, if you're trying to use decimals, why not just use a double:
double x = 0.0004;
double n = x*100;

Floating point in Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why does (360 / 24) / 60 = 0 … in Java
Having problems with floats and longs in Java
float f = 0.100f;
f = 3/180;
At the minute i am trying to do something like this with object and their attributes, but even to this simplest form my program returns 0.0.
I have tried this with Longs as well as still the same result. It's been a long day and maybe it's something simple but I'm at a brick wall.
Your expression 3/180 is performing an integer division, and it is then casting that into the float f. In integer division, 3/180 will return 0, and this is what you are seeing.
What you probably want to do is just add a decimal point to your numbers: f = 3.0/180.0;
3/180 is integer division.
Therefore, the result is truncated to an integer.
You need to perform floating-point division: 3/180f
You do an integer division. So you get an int which is casted back to a float. Try this:
f = 3/180.0;
or
f = 3/180f;
Try 3.0/180. Otherwise, you are dividing two integers and you run into integer truncation. When you do integer division the result is also an integer, not a floating point number.

Categories