Modulus Operation Returning Weird Results - java

This program divides a number and calculates its quotient and remainder. But I'm getting odd results for the modulus operation.
public String operater(int arg1, int arg2) throws IllegalArgumentException
{
int quotient;
int remainder;
String resString;
// Check for Divide by 0 Error.
if(arg2 == 0)
{
throw new IllegalArgumentException("Illegal Argument!");
}
else
{
quotient = arg1 / arg2;
remainder = arg1 % arg2;
resString = "Quotient: " + Integer.toString(quotient) +
Remainder: " + Integer.toString(remainder);
}
return resString;
}
58585 / -45 gives the quotient as -1301 and remainder as 40. But Google says that 58585 % -45 = -5. I think the reason that there are special rules to dealing with signs when doing signs.
From Modulo Operations:
"However, this still leaves a sign ambiguity if the remainder is
nonzero: two possible choices for the remainder occur, one negative
and the other positive, and two possible choices for the quotient
occur. Usually, in number theory, the positive remainder is always
chosen, but programming languages choose depending on the language and
the signs of a and/or n.[6] Standard Pascal and ALGOL 68 give a
positive remainder (or 0) even for negative divisors, and some
programming languages, such as C90, leave it to the implementation
when either of n or a is negative. See the table for details. a modulo
0 is undefined in most systems, although some do define it as a."
I want to fix my program but, I don't understand what that means.

Depends on what you want. In math, and in some programming languages if the modulo is not zero, then it has the same sign as the divisor, treating integer division as truncating towards negative infinity. In other programming languages, if the modulo is not zero, it has the same sign as the dividend, treating integer division as truncating towards zero. Some programming languages include both a modulo operator (sign same as divisor) and remainder operator (sign same as dividend).
With the mathematical type of modulo, then r = (a + k*b)%b returns the same value for r regardless if k is negative, zero, or positive. It also means that there are only b possible values for any dividend modulo b, as opposed to the other case where there are 2*b - 1 possible values for a dividend modulo b, depending on the sign of the dividend.
C example to make modulo work the way it does in mathematics:
int modulo(int n, int p)
{
int r = n%p;
if(((p > 0) && (r < 0)) || ((p < 0) && (r > 0)))
r += p;
return r;
}

Related

How to check if a ≤ b with an epsilon precision

So I have two doubles, a and b, and I need to check if a ≤ b with the precision of a given epsilon.
So to check if a == b I need to do this (a and b are doubles, EPSILON is a final double, in my case 0.001):
Math.abs(a - b) < EPSILON
My idea as an answer to my own question is:
a < EPSILON + b
My problem is that with a precision of epsilon, what would be the difference between just less than and less than or equal in the final result, maybe someone has a better way to write it?
You don't want to write, a < EPSILON+b, because if b is large, then you might have b == EPSILON+b, and then a < EPSILON+b would fail if a and b were exactly equal.
(a-b) < EPSILON works.
When comparing numbers with "epsilon precision" you consider numbers to be the same if they are within EPSILON, so "a < b, with epsilon precision" is actually:
(a-b) <= -EPSILON
If you can use BigDecimal, then use it, else:
/**
*#param precision number of decimal digits
*/
public static boolean areEqualDouble(double a, double b, int precision) {
return Math.abs(a - b) <= Math.pow(10, -precision);
}
UPDATE: this post is wrong, see comments. #matttimmens' answer seem legit. (I still have to check corner cases)
UPDATE 2 I checked and learned. I thought I'd find corner cases like with integers. In Java, (Integer.MIN_VALUE == ((-Integer.MIN_VALUE))) is true. This is because integer numbers (as in: non-decimal, non-floating point) have asymmetrical ranges:
first positive number is 0, first negative number is -1, and thus
byte: MAX_VALUE is 127, while MIN_VALUE is -128, so MAX_VALUE != -MIN_VALUE and MIN_VALUE != MAX_VALUE
also goes for short, int, long
This, mixed together with silent integer overflow, creates problems when working in the extreme corners, especially the off-by-one problem:
final int a = Integer.MIN_VALUE;
final int b = Integer.MAX_VALUE;
final int eps = 1;
System.out.println("a-b = " + (a - b));
System.out.println((a - b) < eps);
a-b results in 1, and 1 < eps is false, though we clearly see that a is a lot smaller than b.
This is one corner case where the algorithm would fail on integers. Mind: the OP was about doubles.
However, floating-point numbers in Java (float, double), or rather, operations on them, compensate, and do not allow for overflows to happen:
(Double.MAX_VALUE + 1) == Double.MAX_VALUE holds true
(Double.MAX_VALUE + Double.MAX_VALUE) == Double.POSITIVE_INFINITY holds true
(-Double.MAX_VALUE + -Double.MAX_VALUE) == Double.NEGATIVE_INFINITY holds true
So before, with integers, the +1 or -1 silent integer overflows caused a problem.
So when adding a +1 (or -1 or any small number) to a really large double variable, the change gets lost to rounding. Thus the corner cases play no role here, and #matttimmens' solution (a-b)<e is as close to the truth as we can get for floating-point variables, rounding left aside.
My old, wrong post:
To counter #matttimmens' reply, run that code:
final double a = Double.MIN_VALUE;
final double b = Double.MIN_VALUE + 0;
final double c = Double.MIN_VALUE + 10;
final double e = 0.001;
System.out.println("Matches 1: " + ((a - b) < e));
System.out.println("Matches 2: " + ((b - a) < e));
System.out.println("Matches 3: " + ((a - c) < e));
System.out.println("Matches 4: " + ((c - a) < e));
Match 3 gives a false result, thus his answer is wrong.
Funny thing is that he thought about vary big numbers, but left the very small numbers unattended.

why does modulus by a large number seem to give a wrong answer in Java

I am trying to find trailing numbers of zeros in a number, here is my code:
public class TrailingZeroes {
public static void bruteForce(int num){ //25
double fact = num; //25
int numOfZeroes = 0;
for(int i= num - 1; i > 1; i--){
fact = fact * (i);
}
System.out.printf("Fact: %.0f\n",fact); //15511210043330984000000000
while(fact % 10 == 0){
fact = fact / 10;
double factRem = fact % 10;
System.out.printf("Fact/10: %.0f\n",fact); //1551121004333098400000000
System.out.printf("FactRem: %.0f\n",factRem); // 2?
numOfZeroes++;
}
System.out.println("Nnumber of zeroes "+ numOfZeroes); //1
}
}
As you can see the fact%10
You use floating point data type illegally.
The float and double primitive types in Java are floating point numbers, where the number is stored as a binary representation of a fraction and a exponent.
More specifically, a double-precision floating point value such as the double type is a 64-bit value, where:
1 bit denotes the sign (positive or negative).
11 bits for the exponent.
52 bits for the significant digits (the fractional part as a binary).
These parts are combined to produce a double representation of a value.
For a detailed description of how floating point values are handled in Java, see the Section 4.2.3: Floating-Point Types, Formats, and Values of the Java Language Specification.
The byte, char, int, long types are [fixed-point][6] numbers, which are exact representions of numbers. Unlike fixed point numbers, floating point numbers will some times (safe to assume "most of the time") not be able to return an exact representation of a number. This is the reason why you end up with 11.399999999999 as the result of 5.6 + 5.8.
When requiring a value that is exact, such as 1.5 or 150.1005, you'll want to use one of the fixed-point types, which will be able to represent the number exactly.
As has been mentioned several times already, Java has a BigDecimal class which will handle very large numbers and very small numbers.
public static void bruteForce(int num) { //25
double fact = num;
// precision was lost on high i
for (int i = num - 1; i > 1; i--)
fact *= i;
String str = String.format("%.0f", fact); //15511210043330984000000000
System.out.println(str);
int i = str.length() - 1;
int numOfZeroes = 0;
while (str.charAt(i--) == '0')
numOfZeroes++;
System.out.println("Number of zeroes " + numOfZeroes); //9
}

How to use Euclid's algorithm to find GCF/GCD?

I have created a method that allows me to find the GCF/GCD of two numbers, and although I have a working code, I don't know how or why it works. I understand Euclid's algorithm, but am not sure how the following snippet uses it.
private int gcd(int a, int b)
{
if (b == 0)
return a;
else if(a ==0)
return b;
else
return gcd(b, a % b);
}
I am especially confused on what it is returning, because why are were returning two values? And what does the a % b do? How does this use Euclid's algorithm?
"the greatest common divisor of two numbers does not change if the
larger number is replaced by its difference with the smaller number."
(wikipedia - Euclidean algorithm)
So, modulo:
Modulo returns the remainder of the integer divison between two integers. Integer division is divison without fractions or floating points. Let's denote integer division as m /\ n.
m /\ n = o;
m % n = p;
o * n + p = m;
As an example,
29 /\ 3 = 9; (3 goes - whole - into 29 9 times)
29 % 3 = 2; (the integer division of 29 into 3 has a remainder of 2)
9 * 3 + 2 = 29; (9 goes into 29 3 times (and 3 goes into 29 9 times), with a remainder of 2)
Note that if m is smaller than n (i.e. m < n), then n goes into m 0 times (m /\ n = 0), so the remainder of the integer division will be m (m % n = m, because o * n + p = m and so (0*n) + p = 0 + p = p = m);
So, how does the function work? let's try using it.
1 - gcd(m, n), m < n
So, if we start out gcd(m, n) with an m that is smaller than n, the only thing that happens on the next nested call to gcd is that the order of the arguments changes: gcd(n, m % n) = gcd(n, m);
2 - gcd(n, m), m < n
Okay, so now the first argument larger than the second.
According to euclid's algorithm, we want to do something to the larger of the two numbers. We want to replace it with the difference between it and the smaller number. We could do m - n a bunch of times. But what m % n does is the exact same as subtracting n from m as many times as possible before doing so would result in a negative number. Doing a subtraction would look like (((m - n) - n) - n) - n) and so on. But if we expand that out, we get:
m - (n * o). Because o * n + p = m, we can see that m - (n * o) = p and p = m % n. So, repeatedly subtracting the smaller from the larger is the same as doing modulo of the larger with the smaller.
In the next step, the second argument may be 0 (if n was a divisor of m). In this case, the function returns n. this is correct because n is a divisor of itself and also, as we've seen, a divisor of m.
Or, the second argument may be smaller than n. That is because the remainder of the integer divison of m into n must be smaller than n - this is because, if the remainder of the division were larger than n, then n could have fit into m one more time, which it didn't; this is an absurd result. Assuming that n is not 0, then the second argument (let's call it p) is smaller than n.
So, we are now calling gcd(n, p), where p < n.
3 - gcd(n, p), p < n
What happens now? well, we are exactly in the same place as we were in the previous paragraph. Now we just repeat that step, i.e. we will continue to call gcd(a, b), until the smaller of the two numbers that are passed into gcd(a ,b) is a divisor of the larger of the two numbers, (meaning that a % b = 0) in which case you simply return the smaller of the two numbers.
1) What does the a % b do?
% is the modulus or remainder operator in Java. The % operator returns the remainder of two numbers. For example 8 % 3 is 2 because 8 divided by 3 leaves a remainder of 2.
2) The Euclidean algorithm is based on the principle that the greatest common divisor of two numbers does not change if the larger number is replaced by its difference with the smaller number. Actually, your gcd function is used a more efficient version of the Euclidean algorithm. This version instead replacing the larger of the two numbers by its remainder when divided by the smaller of the two (with this version, the algorithm stops when reaching a zero remainder). This was proven by Gabriel Lamé in 1844 (https://en.wikipedia.org/wiki/Euclidean_algorithm)
3) Your gcd function's not returning two values, it's a recursive function. The recursive function is a function which either calls itself or is in a potential cycle of function calls. In case of your gcd function, it will be repeat until one of two parameters become zero and the gcd value is the remain parameter.
You could learn more about recursive function at this link.
http://pages.cs.wisc.edu/~calvin/cs110/RECURSION.html
Given that your question has a few components, I’ll discuss the evolution of Euclid’s classical algorithm into the recursive method you presented. Please note that the methods presented here assume that a >= b
The method below most likely implements the algorithm that you are familiar with, which repeatedly subtracts b (the smaller number) from a (the larger number), until it is no longer larger or equal to b. If a == 0, there is no remainder, giving b as the GCD. Otherwise, the values of a and b are swapped and repeated subtraction continues.
public int classic_gcd(int a, int b) {
while (true) {
while (a >= b)
a = a - b;
if (a == 0)
return b;
int c = b;
b = a;
a = c;
}
}
Since the inner while loop, essentially calculates the reminder of a divided by b, it can be replaced with the modulus operator. This greatly improves the convergence rate of the algorithm, replacing a potentially large number of subtractions with a single modulus operation. Consider finding the GCD of 12,288 and 6, which would result in over 2,000 subtraction. This improvement is shown in the modified method below.
public int mod_gcd(int a, int b) {
while (true) {
int c = a % b;
if (c == 0)
return b;
a = b;
b = c;
}
}
Lastly, the modified algorithm can be expressed as a recursive algorithm, that is, it calls upon itself, as follows:
public int recurse_gcd(int a, int b) {
if (b == 0)
return a;
else
return recurse_gcd(b, a % b);
}
This method accomplishes the same as before. However, rather than looping, the method calls itself (which if not checked is an endless loop too). The swapping of values is accomplishing by changing the order of the arguments passed to the method.
Mind you, the methods above are purely for demonstration and should not be used in production code.

Java integer division doesn't give floor for negative numbers

I was trying to use java's integer division, and it supposedly takes the floor. However, it rounds towards zero instead of the floor.
public class Main {
public static void main(String[] args) {
System.out.println(-1 / 100); // should be -1, but is 0
System.out.println(Math.floor(-1d/100d)); // correct
}
}
The problem is that I do not want to convert to a double/float because it needs to be efficient. I'm trying to solve this with a method, floorDivide(long a, long b). What I have is:
static long floorDivide(long a, long b) {
if (a < 0) {
// what do I put here?
}
return a / b;
}
How can I do this without a double/float?
floorDiv() from Java.Math that does exactly what you want.
static long floorDiv(long x, long y)
Returns the largest (closest to positive infinity) long value that is less than or equal to the algebraic quotient.
Take the absolute value, divide it, multiply it by -1.
Weird bug.
You can use
int i = (int) Math.round(doubleValToRound);
It will return a double value that you can cast into an int without lost of precission and without performance problems (casts haven't a great computational cost)
Also it's equivalent to
int a = (int) (doubleValToRound + 0.5);
//in your case
System.out.println((int) ((-1 / 100) + 0.5));
With this last one you won't have to enter into tedious and unnecesary "if" instructions. Like a good suit, its valid for every moment and has a higher portability for other languages.
This is ugly, but meets the requirement to not use a double/float. Really you should just cast it to a double.
The logic here is take the floor of a negative result from the integer division if it doesn't divide evenly.
static long floorDivide(long a, long b)
{
if(a % b != 0 && ((a < 0 && b > 0) || (a > 0 && b < 0)))
{
return (a / b - 1);
}
else
{
return (a / b);
}
}
Just divide the two integers. then add -1 to the result (in case the absolute value of both numerator and denominator are not same). For example -3/3 gives you -1, the right answer without adding -1 to the division.
Since a bit late, but you need to convert your parameters to long or double
int result = (int) Math.floor( (double) -1 / 5 );
// result == -1
This worked for me elegantly.
I would use floorDiv() for a general case, as Frank Harper suggested.
Note, however, that when the divisor is a power of 2, the division is often substituted by a right shift by an appropriate number of bits, i.e.
x / d
is the same as
x >> p
when p = 0,1,...,30 (or 0,1,...,62 for longs), d = 2p and x is non-negative. This is not only more effective than ordinary division but gives the right result (in mathematical sense) when x is negative.

Java Modulo Not Working? [duplicate]

This question already has answers here:
C: The Math Behind Negatives and Remainder
(2 answers)
Closed 9 years ago.
If I ask java for:
System.out.print(-0.785 % (2*Math.PI));
And print the result, it shows -0.785 when it should be printing 5.498... Can anyone explain me why?
The first operand is negative and the second operand is positive.
According to the JLS, Section 15.17.3:
[W]here neither an infinity, nor a zero, nor NaN is involved, the
floating-point remainder r from the division of a dividend n by a
divisor d is defined by the mathematical relation r = n - (d · q)
where q is an integer that is negative only if n/d is negative and
positive only if n/d is positive, and whose magnitude is as large as
possible without exceeding the magnitude of the true mathematical
quotient of n and d.
There is no requirement that the remainder is positive.
Here, n is -0.785, and d is 2 * Math.PI. The largest q whose magnitude doesn't exceed the true mathematical quotient is 0. So...
r = n - (d * q) = -0.785 - (2 * Math.PI * 0) = -0.785
Ok, I'm not going to explain it better than the other answer, but let's just say how to get your desired results.
The function:
static double positiveRemainder(double n, double divisor)
{
if (n >= 0)
return n % divisor;
else
{
double val = divisor + (n % divisor);
if (val == divisor)
return 0;
else
return val;
}
}
What's happening:
If n >= 0, we just do a standard remainder.
If n < 0, we first do a remainder, putting it in the range (-divisor, 0], then we add divisor, putting it in our desired range of (0, divisor]. But wait, that range is wrong, it should be [0, divisor) (5 + (-5 % 5) is 5, not 0), so if the output would be divisor, just return 0 instead.

Categories

Resources