110 likes | 222 Views
CSE115: Introduction to Computer Science I. Dr. Carl Alphonce 219 Bell Hall Office hours: M-F 11:00-11:50 645-4739 alphonce@buffalo.edu. Exam 4. Monday (12/6) Exam 4 review Wednesday (12/8) Exam 4 Friday (12/10) Final exam review. This week. Primitives (floating point numbers)
E N D
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 219 Bell Hall Office hours: M-F 11:00-11:50 645-4739 alphonce@buffalo.edu
Exam 4 • Monday (12/6) Exam 4 review • Wednesday (12/8) Exam 4 • Friday (12/10) Final exam review
This week • Primitives (floating point numbers) • Inheritance (tie up loose ends) • Lab discussion • maybe on Friday, if time allows
Today • Floating point numbers • inexact representation • type casting/coercion • If time: • for loop • switch/case
Primitives in Java • Java has eight primitive types • boolean • integral types: • signed: long, int, short, byte • unsigned: char • floating point types: double, float • Values of the primitive types are not objects • no properties • no capabilities
double • values: 0.0, 1.0, -3.5, 3141.5926535e-3 • inexact representation (!) • operations: + - * / 5.0 + 2.0 = 7.0 + double X double double 5.0 – 2.0 = 3.0 - double X double double 5.0 * 2.0 = 10.0 * double X double double 5.0 / 2.0 = 2.5 / double X double double
floating point types’ representation • both double and float use the IEEE754 representation scheme • size of representation differs according to type: • the representation of a float is 4 bytes wide • the representation of a double is 8 bytes wide • main point: values of different types have different representations – you can’t “mix and match”!
Things to watch for! • Representation is inexact • e.g. has a truncated representation • 0.1 does not have an exact representation • representation is in terms of powers of 2 • Mixing magnitudes • it is possible that x+y is the same as x! • 1.0e-15 + 1.0e-15 2.0 e-15 • 1.0e+15 + 1.0e-15 1.0 e+15 (whoops!) • Round-off errors – comparisons! • double d = 0.1; • double pointNine = d+d+d+d+d+d+d+d+d; • pointNine is not the same as 0.9 (whoops!)
mixing types in expressions • Operators such as +, -, * and / are overloaded: the same name has many different values + overloaded as String concatenation too! “Good” + “ ” + “morning!” “Good morning!” • What happens in an expression which mixes values of different types? 5 + 2.5 = ???? 5 is coerced to its equivalent double value, 5.0: 5.0 + 2.5 = 7.5 • Type coercion happens only from “smaller” type to “larger” type (e.g. int double, not double int)
relational operators • We can form expressions like: x < y which have a value of true or false (i.e. the type of this expression is boolean) • relational operators: < <= > >= == • BUT: be careful doing == with floating point numbers!
Equality testing • Equality testing: • of primitive values: == • of objects: equals method • Consider: Foo a = new Foo(); Foo c = a; Foo b = new Foo(); • what is value of what is value of (a==b) (a==c)