package class3_2_OfficeHours_CharArithmeticAndBigFloats_start;// Dr. Yoder. MSOE. 21 March 2017 /** * This is an example to answer the question: * Both float and int use 32 bits. Why is * the maximum value for int only 2 billion, while * long can go all the way to to 3.4 * 10^38? * * The answer is that it is true an int can only store * about four billion numbers (two billion positive, and two * billion negative). * * But float can also only hold about four billion numbers. * Instead of laying them out like this * 0 * * * * * * * * * * It lays them out more like this * 0 * * * *** * * * There are the same 4 billion numbers, but they are * spread out more so they can reach even larger values. * * For example, consider the largest floating-point value. * In the code below we find that it has a value of * 3.4028235 * 10^38 * The next largest number that a float can hold is * 3.4028234 * 10^38 * Which is 10_000_000_000_000_000_000_000_000_000_000 * smaller! That's a huge step! */ public class BigFloats { public static void main(String[] args) { float bigFloat = Float.MAX_VALUE; System.out.println("bigFloat = " + bigFloat); System.out.println("bigFloat-1 = " + (bigFloat - 1)); System.out.println("bigFloat-2e31f = " + (bigFloat - 2e31f)); System.out.println("bigFloat-2e31f = " + (bigFloat - 20_000_000_000_000_000_000_000_000_000_000f)); System.out.println("2e31f = " + (20_000_000_000_000_000_000_000_000_000_000f)); System.out.println("3.4028234E38 = " + 3.4028234E38); /* Further exploration: * Can we subtract anything from bigFloat to get to the next biggest float? */ System.out.println("bigFloat - 3.4028234E38= " + (bigFloat - 3.4028234E38f)); /* What? It's zero!?!?!? How can such a huge gap be rounded away? * Let's do it with doubles: */ System.out.println("(double)bigFloat - 3.4028234E38= " + ((double)bigFloat - (double)3.4028234E38f)); /* Still 0? One more try: */ System.out.println("(double)bigFloat - 3.4028234E38= " + ((double)bigFloat - 3.4028234E38)); /* 6_638_528_867_415_850_000_000_000_000_000 * Wow! That's a big number to round away! * And why isn't it * 10_000_000_000_000_000_000_000_000_000_000? * * Summary: Floats and doubles can hold very large numbers, * but they are very far apart. * * The total number of values a double or float can have * is the same as the number of values a long or int can have, * but they are more spread out. */ } }