Java: Converting absolute value of BigInteger into intValue() resulting negative value [duplicate] - java

This question already has answers here:
How does Java handle integer underflows and overflows and how would you check for it?
(12 answers)
BigInteger.pow(BigInteger)?
(9 answers)
Closed 3 years ago.
I'm trying to do a BigInteger exponent calculation. For my calculation, I am trying to subtract m1 from m2 (both are BigInteger) and get a positive value, but if I convert this positive number to an int number, I end up getting a negative value.
BigInteger m1 = new BigInteger("2905012217");
BigInteger m2 = new BigInteger("534500746");
int exp = m2.subtract(m1).abs().intValue();
System.out.println(exp);
BigInteger g1 = new BigInteger("2");
BigInteger output_test_g1 = g1.pow(exp);
output:
m1:2905012217
m2:534500746
exp:-1924455825
Error:
Exception in thread "main" java.lang.ArithmeticException: Negative exponent
at java.base/java.math.BigInteger.pow(BigInteger.java:2401)
at FHEv1.homomorphicEqualityTest(FHEv1.java:195)
at FHEv1.main(FHEv1.java:323)

Integer overflow. How does Java handle integer underflows and overflows and how would you check for it?
Too high and overflow to Integer.MIN_VALUE and continue counting if nessecary. Too low and go to Integer.MAX_VALUE and continue counting if nessecary.
For example,
int A = Integer.MAX_VALUE;
A++;
//A should be Integer.MIN_VALUE, correct me if I am wrong

Related

Stream api reduce method returns negative value when trying to sum up large numbers [duplicate]

This question already has answers here:
How does Java handle integer underflows and overflows and how would you check for it?
(12 answers)
Closed 1 year ago.
I am trying to do sum of numbers in a list using stream api reduce method. It gives correct result for smaller numbers. But when I give larger numbers then it returns a negative number which is not correct.
Here is my code
public void sumOfNum(List<Integer> numbers) {
long result = numbers.stream().reduce(0, (a, b) -> a + b);
System.out.print(result);
}
Testcase 1(passed)
Input
12345, 2343,4324,2323,24234
Output
45569
Testcase 2(failed)
Input
256741038, 623958417,623958417,714532089 , 714532089
Output
-1361245246
You are adding them as Integers and java has limit for Integer value 2147483647.
If you pass this max value you will start to count from minimum value
Integer.MAX_VALUE + 1 = -2147483648.
You are performing an Integer addition with your current code. My assumption is that you are aware of the numeric overflow that could occur and that's the reason for long type of result. Things would be in place once you map the values of the stream to Long before summing them.
long result = numbers.stream()
.map(Long::valueOf)
.reduce(0L, Long::sum);
Or simply put:
long result = numbers.stream()
.mapToLong(val -> val)
.sum();

Java Long Min and Max not exact as mentioned in docs [duplicate]

This question already has answers here:
Java Math.pow() Rounding Error
(4 answers)
Squaring Numbers in java using Math.pow getting error of precision
(5 answers)
why java Math.pow arguments double?
(1 answer)
Java always give me wrong result with huge numbers [duplicate]
(3 answers)
Closed 5 years ago.
As per java doc, the Long.MIN_VALUE is -2^63 and Long.MAX_VALUE is 2^63 - 1.
But Long.MIN_VALUE actual value is -2^63 - 1 and Long.MAX_VALUE value is 2^63 if I compute it like here:
long min = -(long) Math.pow(2, 63);
long max = (long) Math.pow(2, 63) - 1;
System.out.println(min);
System.out.println(max);
Over all the range between minimum and maximum value is the same but the actual values are not. Is my understanding of the above code wrong?
My bad, its the way I checked that lead to wrong values. The following is the simplest way I could think of to verify 2 power values in java.
long num = 1;
for(long count = 0; count < 63; count ++) {
num = num * 2;
}
System.out.println(num);
}
Math.pow's return value is double.
double can only exactly represent all integer values up to 2^53 - 1, and down to -2^53, because it only has 53 mantissa bits.
The error is simply in how you are attempting to check these values.

Dividing two ints into a big decimal [duplicate]

This question already has answers here:
ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"
(9 answers)
Closed 7 years ago.
I'm conducting an experiment in which we will occasionally have to divide small numbers by large numbers, for example: 4 / 90,000. Using a double results in a 4.444444444e. I was hoping perhaps a BigDecimal could handle this arithmetic and give me a meaningful decimal, but my implementation throws an error:
int count = 4;
int total = 90,000;
er = BigDecimal.valueOf(count).divide(BigDecimal.valueOf(total));
Error is:
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide(BigDecimal.java:1616)
Update: I am interesting in atleast 3 decimal places of precision.
You could pass a MathContext to the division method call. Something like,
int count = 4;
int total = 90000;
BigDecimal er = BigDecimal.valueOf(count).divide(BigDecimal.valueOf(total),
MathContext.DECIMAL128);
System.out.println(er);
And I get
0.00004444444444444444444444444444444444

Round up when multiplying an integer by 0.5 [duplicate]

This question already has answers here:
Always Round UP a Double
(8 answers)
Closed 7 years ago.
Is there a way to automatically round up a value in java?
For example:
//generate a random integer value
int randomVal = RandomHelper.nextIntFromTo(1, otherVal);
/* then divide the integer value in half... the error I am getting is that its a double, probably
because the number generated isn't an even number, but I NEED it to be an integer. Can I round up?*/
int value = randomVal * 0.5;
You can add 1 then divide by 2 instead of multiplying by 0.5. That way, you avoid a floating point operation followed by a conversion to int.
int value = (randomVal + 1) / 2;
Use Math.ceil():
int value = (int)Math.ceil(randomVal * 0.5);

BigInteger returning negative numbers [duplicate]

This question already has answers here:
Why do these two multiplication operations give different results?
(2 answers)
Closed 8 years ago.
why this math return negative numbers for some numbers:
int x = 351;
String bigValue= ((50*x*x*x-150*x*x+400*x)/3) + "";
BigInteger resultInteger = new BigInteger(bigValue);
System.out.println(resultInteger);
result -> 714612600
but if i use 352
result -> -710900565
for x=500 -> 639244234
WHY?
This line here:
(50*x*x*x-150*x*x+400*x)/3
Is using integers, which can overflow. If an integer hits the max (2^31-1), it will overflow to -2^31.
You need to use BigIntegers here, something like this:
Biginteger bx = new BigInteger(x);
BigInteger new BigInteger(50).multiply(bx.pow(3)).multiply(new BigInteger(-150))
.multiply(bx.pow(2)).multiply(new BigInteger(400)).multiply(bx).divide(3);

Categories

Resources