The Department of Computer Science & Engineering
cse@buffalo
STUART C. SHAPIRO: CSE 115 C

CSE 115
Introduction To Computer Science for Majors I
Lecture C
Lecture Notes #25
Stuart C. Shapiro
Spring, 2007


Floating Point Numbers: double

Floating point numbers are numbers used for measuring.
(Currency: integers should really be used for currency, but many use floating point numbers anyway.)
The primitive floating point type we will discuss is double, and its wrapper class is java.lang.Double.
Write a double constant literal as a sequence of digits without a comma, but with a decimal point, and optionally followed by an "e" and then by an integer.
The floating point operators are:
OperatorMeaning
+addition or unary plus
-subtraction or unary minus
*multiplication
/division
%modulus (remainder)

See java.lang.Math for some functions provided by the Java library.

Floating Point Numbers: Cautionary Tales

  1. non-exact representation of 0.1
    Try: for (double x = .1; x <= 1.; x += .1) {System.out.println(x);}

  2. non-use of ==
    Try: 0.3 == 0.2 + 0.1
    Compare: Math.abs(0.3 - (0.2 + 0.1)) < .005

  3. non-associativity of +
    Try:
    2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2.0
    
    2.0+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16
    
    2.0+(2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16)
    
    2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2.0
    == 2.0+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16+2e-16
    

First Previous Next

Copyright © 2007 by Stuart C. Shapiro. All rights reserved.

Last modified: Fri Nov 30 14:56:58 EST 2007
Stuart C. Shapiro <shapiro@cse.buffalo.edu>