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

multiply(Double a, Double b) where a=2.3 and b=5.1 does not return expected result.

XMLWordPrintable

    • x86_64
    • windows_10

      ADDITIONAL SYSTEM INFORMATION :
      Windows 10, Java version "1.8.0_201"

      A DESCRIPTION OF THE PROBLEM :
      package com.askmeipaas.java;

      public class Multiple {
          static Double multiply(Double a, Double b) {
                  return a * b;
          }

          public static void main(String[] args) {
              Double a = 0.1;
              for (int ia=0; ia<200; ia++) {
                  Double b = 0.1;
                  for (int ib=0; ib<200; ib++) {
                      //All results are correct
                      System.out.printf("Multiplying %f, %f, result: %f \n",a,b,Multiple.multiply(a,b));
                      ib++;
                      b = b + 0.1;
                  }
                  a = a + 0.1;
                  ia++;
              }

              System.out.println(Multiple.multiply(2.3, 5.1)); // Returns 11.729999999999999
          }
      }

      The multiply function in the loop is working fine while it is not returning correct precision with the value of a=2.3 and b=5.1 when tested in the last print statement.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Run the above program

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      11.73
      ACTUAL -
      11.729999999999999

      ---------- BEGIN SOURCE ----------
      package com.askmeipaas.scalabasics;

      public class Multiple {
          static Double multiply(Double a, Double b) {
                  return a * b;
          }

          public static void main(String[] args) {
              Double a = 0.1;
              for (int ia=0; ia<200; ia++) {
                  Double b = 0.1;
                  for (int ib=0; ib<200; ib++) {
                      //All results are correct
                      System.out.printf("Multiplying %f, %f, result: %f \n",a,b,Multiple.multiply(a,b));
                      ib++;
                      b = b + 0.1;
                  }
                  a = a + 0.1;
                  ia++;
              }

              System.out.println(Multiple.multiply(2.3, 5.1)); // Returns 11.729999999999999
          }
      }

      ---------- END SOURCE ----------

      FREQUENCY : always


            psonal Pallavi Sonal (Inactive)
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: