Comparing Data. Comparing Floating Point Values. Comparing Float Values. CS257 Computer Science I Kevin Sahr, PhD

Similar documents
ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Conditionals and Loops

CS1004: Intro to CS in Java, Spring 2005

Lab 8: IF statement. Conditionals and Loops. Copyright 2012 Pearson Education, Inc.

Program Development. Chapter 3: Program Statements. Program Statements. Requirements. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 3: Program Statements

Java Flow of Control

Chapter 4: Conditionals and Loops

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Program Planning, Data Comparisons, Strings

Chapter 4: Conditionals and Loops

More Programming Constructs -- Introduction

COMP Primitive and Class Types. Yi Hong May 14, 2015

CMPT 125: Lecture 3 Data and Expressions

Chapter 4: Conditionals and Loops

CMPT 125: Lecture 4 Conditionals and Loops

Conditional Programming

Chapter 3: Operators, Expressions and Type Conversion

BRANCHING if-else statements

Topics. Chapter 5. Equality Operators

Conditionals and Loops Chapter 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CIS 110: Introduction to Computer Programming

Conditional Statements

Algorithms and Conditionals

Visual C# Instructor s Manual Table of Contents

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

COMP combinational logic 1 Jan. 18, 2016

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Logical Operators and switch

Operators. Java operators are classified into three categories:

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

I Internal Examination Sept Class: - BCA I Subject: - Principles of Programming Lang. (BCA 104) MM: 40 Set: A Time: 1 ½ Hrs.

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Exam 1. CSC 121 Spring Lecturer: Howard Rosenthal. March 1, 2017

Lecture 9. Monday, January 31 CS 205 Programming for the Sciences - Lecture 9 1

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

Conditionals. For exercises 1 to 27, indicate the output that will be produced. Assume the following declarations:

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Operators and Expressions

Full file at

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

4. Number Representations

Basics of Java Programming

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?

COMP2121: Microprocessors and Interfacing. Number Systems

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Chapter 6 Primitive types

PYTHON- AN INNOVATION

COMP-202: Foundations of Programming. Lecture 5: More About Methods and Data Types Jackie Cheung, Winter 2016

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Operators & Expressions

Computational Expression

Bits, Words, and Integers

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Chapter 2: Using Data

Basic data types. Building blocks of computation

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Control Structures in Java if-else and switch

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007

Java enum, casts, and others (Select portions of Chapters 4 & 5)

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Improved algorithm. Java code. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm

Chapter 4: Basic C Operators

Chapter 2: Data and Expressions

CS 115 Lecture 8. Selection: the if statement. Neil Moore

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Chapter 2: Data and Expressions

JAVA OPERATORS GENERAL

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Flow Control. So Far: Writing simple statements that get executed one after another.

ECE 122 Engineering Problem Solving with Java

Hexadecimal Numbers. Journal: If you were to extend our numbering system to more digits, what digits would you use? Why those?

Flow of Control. Chapter 3

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement

Operators. Lecture 3 COP 3014 Spring January 16, 2018

Logical and Bitwise Expressions

COMS 1003 Fall Introduction to Computer Programming in C. Bits, Boolean Logic & Discrete Math. September 13 th

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Decisions in Java IF Statements

Birkbeck (University of London) Department of Computer Science and Information Systems. Introduction to Computer Systems (BUCI008H4)

Chapter 4. Operations on Data

CS112 Lecture: Working with Numbers

Control flow, conditionals, boolean expressions, block statements, nested statements. Course website:

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

CSE 452: Programming Languages. Outline of Today s Lecture. Expressions. Expressions and Control Flow

LECTURE 3 C++ Basics Part 2

Lecture Set 2: Starting Java

Operators in C. Staff Incharge: S.Sasirekha

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Problem with Scanning an Infix Expression

Prof. Navrati Saxena TA: Rochak Sachan

Chapter 2: Data and Expressions

Lecture Set 2: Starting Java

Transcription:

1 CS257 Computer Science I Kevin Sahr, PhD Lecture 6: Comparing Data and Complex Boolean Expressions Comparing Data 2 When comparing data it's important to understand the nuances of certain data types Let's examine some key situations: Comparing floating point values for equality Comparing characters Comparing objects (vs. comparing object references) Comparing Strings Comparing Floating Point Values 3 You should rarely use the equality operator (==) when comparing two floating point values (float or double) Two floating point values are equal only if their underlying binary representations match exactly But floating point representations actually only store approximations to real numbers Floating point computations often introduce very small errors known as rounding errors Therefore, in many situations, we consider two floating point numbers to be equal if they differ by some very small amount, even if they aren't exactly equal Comparing Float Values 4 To determine the equality of two floats, the following technique is often used: if (Math.abs(f1 - f2) < TOLERANCE) System.out.println ("Essentially equal"); If the difference between the two floating point values is less than the tolerance, they are considered to be equal The tolerance should be set to an appropriate level for your problem, such as 0.0000001

Representing Money 5 In applications where rounding error is unacceptable values are often represented internally using appropriately scaled integers For example, monetary values might be represented as an integer number of 1/100th s of a cent EX: $123.45 could be stored internally as the integer value 1234500 converted to/from floating point values for output and input If values are represented this way, they can be compared using == (just like any other integers) Comparing Characters 6 Java character data uses the Unicode character set Unicode specifies a particular numeric value for each character, and therefore an ordering We can use relational operators on character data based on the Unicode ordering EX: the character '+' is less than the character 'J' because the numeric value of '+' comes before the numeric value of 'J' in the Unicode character set Comparing Characters 7 It is often useful to note that in Unicode the digit characters (0-9) are contiguous and in order Likewise, the uppercase letters (A-Z) and lowercase letters (a-z) are contiguous and in order Characters Unicode Values 0 9 48 through 57 A Z 65 through 90 a z 97 through 122 Comparing Objects 8 The == operator can be applied to objects but it returns true only if the two references are aliases of each other (i.e., they refer to the same object) more often we want to compare objects based on their internal values The equals method is defined for all objects, but unless we redefine it when we write a class, it has the same semantics as the == operator When you write a class, you can redefine the equals method to return true or false under whatever conditions are appropriate for instances of your class

Comparing Strings 9 Remember that in Java a String is an object The equals method can be called with Strings to determine if they contain exactly the same characters in the same order The equals method returns a boolean result if (name1.equals(name2)) System.out.println ("Same name"); Comparing Strings Since Strings are objects, we cannot use the relational operators to compare strings 10 using the relational operators will compare the addresses of the Strings, which is probably not what we want! The String class contains a method called compareto to determine if one string comes before another Strings are compared based on lexicographic ordering The characters in the String are compared from firstto-last until a difference is found compareto Method for Strings 11 The method invocation name1.compareto(name2) returns zero if name1 and name2 are equal (contain the same characters) returns a negative value if name1 is less than name2 returns a positive value if name1 is greater than name2 EX: if (name1.compareto(name2) == 0) System.out.println ("Same name"); else if (name1.compareto(name2) < 0) System.out.println (name1 + "comes first"); else System.out.println (name2 + "comes first"); Lexicographic Ordering 12 Lexicographic ordering is not strictly alphabetical when uppercase and lowercase characters are mixed For example, the string "Great" comes before the string "fantastic" because all of the uppercase letters come before all of the lowercase letters in Unicode Also, short strings lexicographically come before longer strings with the same prefix Therefore "book" comes before "bookcase"

Complex Boolean Expressions 13 So far we have only worked with simple boolean simple boolean do not contain logical operators EX: num1 <= num2 name1.equals(name2) atree.getisalive() somebooleanvariable Simple boolean can be combined using logical operators to create complex boolean Logical Operators 14 The Java logical operators are:! Logical NOT && Logical AND Logical OR logical operators take boolean operands Logical NOT is a unary operator (it operates on one operand) Logical AND and logical OR are binary operators (each operates on two operands) involving logical operators are boolean they evaluate to either true or false Logical NOT 15 The logical NOT operation is also called logical negation or logical complement If some boolean expression a is true, then!a is false; if a is false, then!a is true Truth Tables 16 logical can be completely defined using a truth table a truth table specifies all possible values for the operands and the resulting value of the logical expression here is the truth table for logical NOT: a!a true false false true

Logical AND and Logical OR 17 The logical AND expression a && b is true if both a and b are true, and false otherwise The logical OR expression a b is true if a or b or both are true, and false otherwise Logical Operators 18 A truth table shows all possible true/false combinations of the operands Since && and each have two operands, there are four possible combinations of conditions a and b here are the combined truth tables for AND and OR: a b a && b a b true true true true true false false true false true false true false false false false Logical Operator Precedence 19 Expressions that use logical operators can form complex conditions. EX: if (total < MAX+5 &&!found) System.out.println ("Processing "); All logical operators have lower precedence than the relational operators Logical NOT has higher precedence than logical AND and logical OR Logical AND has higher precedence than logical OR Parenthesis can always be used to override precedence (or to minimize confusion) Truth Tables 20 Specific complex boolean can be evaluated using truth tables EX: total < MAX found!found total < MAX &&!found false false true false false true false false true false true true true true false false

Steps: First Create the Columns 1. Create a column for the expression to be evaluated 2. Find the logical operator in the expression with the lowest precedence 3. Create a column to the left of the expression for each of the operands of that logical operator 4. For each of the newly created columns that are themselves complex boolean, repeat steps 2 and 3 for that expression 5. Continue until all operands are simple boolean 6. Rearrange the columns (if needed) so that the columns containing simple boolean are the left-most columns 21 Checking the Columns 22 You now have all the columns The rightmost column should contain the expression being evaluated The left-most columns should consist of all the simple boolean contained in the expression being evaluated each column in between should provide the truth values for a single logical operator involving operands to the left of it Steps: Then Create the Rows 23 1. The number of rows will be the number of unique combinations of the simple boolean 1. N boolean requires 2 N rows 2. Fill-in the columns beneath the simple boolean with all possible unique true/false combinations of those 3. Fill-in the remainder of each row from left-to-right by evaluating each column s expression using the operand truth values given to the left on the same row Creating a Truth Table 24 Example: total < MAX found!found total < MAX &&!found false false true false false true false false true false true true true true false false

Short-Circuited Operators The processing of logical AND and logical OR is short-circuited If the left operand is sufficient to determine the result, the right operand is not evaluated EX: if (count!= 0 && total/count > MAX) System.out.println ("Testing "); In this example if count is 0, then the first operand of && is false, and therefore the entire complex boolean expression is false 25 doesn t matter whether or not total/count > MAX This type of processing must be used consciously and carefully! Lecture 6 Vocabulary 26 rounding error lexicographic ordering simple boolean logical operators complex boolean unary operator binary operator truth table short-circuited operators