0

So one of my students were working on basic equations in computer science and one of them had a weird bug when they wrote the following code.

import java.io.*;
import java.util.*;

public class randomnum{


public static void main(String[] args){

   double incorrectnum = 4.3+6.26;
   System.out.println(incorrectnum);
   double correctnum = 4.2+6.36;
   System.out.println(correctnum);
}

here, the two print statements should be identical, 10.56. However, the first double prints 10.559999999999 and the other one prints 10.56. For the life of me, I can't fathom why. they're logically identical and both carry any numbers the same way (in this case carrying over 0 numbers), so I don't see where the discrepancy occurs. Any insight would be great!

I tried multiple different double equations and almost all of them worked as intended besides this one.

  • *So one of my students* -- if you teach programming, you surely need to understand what floating-point arithmetic is. – access violation Oct 26 '22 at 18:36
  • That is not a bug. That's because the computer uses binary system internally and only accepts and prints in decimal system. In binary system, 4.3 is 100.0100110011... and 6.26 is 110.010000101... The result is not weird, but totally correct. If you need exact result, you can use `BigDecimal` instead – Christoph S. Oct 26 '22 at 19:12
  • If you are teaching programming, you ***MUST*** read and understand the following: [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Jim Garrison Oct 26 '22 at 19:54

0 Answers0