Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-4639626

The % is currently unable to deal with negative numbers properly

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Not an Issue
    • Icon: P4 P4
    • None
    • 1.4.0
    • core-libs



      Name: jk109818 Date: 02/19/2002


      FULL PRODUCT VERSION :
      J2SE 1.3.1 -b24

      FULL OPERATING SYSTEM VERSION :
      glibc-2.2.4-19.3
      Linux (hostname) 2.4.9-6
      Distribution RedHat 7.x

      ADDITIONAL OPERATING SYSTEMS :
      I have also tested this on an UtraSparc 10, and the same
      thing happens.



      A DESCRIPTION OF THE PROBLEM :
      When performing modulo arithmetic on negative numbers the
      current output is incorrect. For example -15%7 is
      interpretted as being -1, it should be 6. Modulo should
      never return a negative number. I probably would not have
      ever run into this except for the fact that I have been
      asked to write a Java implementation of the Enigma Machine
      for a professor.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      1.Simply use System.out.println(-15%7);


      EXPECTED VERSUS ACTUAL BEHAVIOR :
      I expected to obtain a positive number, by definition a
      modulo should always be positive. Instead a -1 was reurned.

      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
      import java.lang.*;
      import java.io.*;


      class Test
      {
          public static void main(String args[])throws IOException
          {

      System.out.println("testing the output of -15 mod 7");

      System.out.println(-15%7);

      System.out.println((int)(-15 - Math.floor((double)-15/7)*7));
          }
      }
      ---------- END SOURCE ----------

      CUSTOMER WORKAROUND :
      The work around for this, is to use the actual formula for
      finding a modulo. As follows: a - floor(a/b) * b.
      When doing this however you need to keep in mind that when
      doing integer arithmetic that Java truncates during division.
      So when you do Math.floor(a/b) with a < 0, you will get the
      ceiling of that result. So the work around code should look
      like this.
      (int)(a - Math.floor((double)a/b)*b) this will produce the
      floor of a/b when a<0 then cast the result back to an int,
      for consistancy.
      (Review ID: 139829)
      ======================================================================

            darcy Joe Darcy
            jkimsunw Jeffrey Kim (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: