Lecture 13. Example. Encapsulation. Rational numbers: a number is rational if it can be defined as the ratio between two integers.

Similar documents
AP Computer Science. TextLab05 Java Assignment. Assignment Purpose: Do not copy this file, which is provided. TextLab05 Student Version

Carleton University Department of Systems and Computer Engineering SYSC Foundations of Imperative Programming - Winter Lab 8 - Structures

CISC 3115 Modern Programming Techniques Spring 2018 Section TY3 Exam 2 Solutions

CIT 590 Homework 6 Fractions

Rational numbers as decimals and as integer fractions

Object Oriented Modeling

Object Oriented Programming COP3330 / CGS5409

Recitation #2 Abstract Data Types, Collection Classes, and Linked List

1 Elementary number theory


Creating a new data type

SOLUTION: Because the fractions have a common denominator, compare the numerators. 5 < 3

CW Middle School. Math RtI 7 A. 4 Pro cient I can add and subtract positive fractions with unlike denominators and simplify the result.

EE 152 Advanced Programming LAB 7

Euclid's Algorithm. MA/CSSE 473 Day 06. Student Questions Odd Pie Fight Euclid's algorithm (if there is time) extended Euclid's algorithm

LAB 7. Objectives: Navin Sridhar D 8 54

Section 2.3 Rational Numbers. A rational number is a number that may be written in the form a b. for any integer a and any nonzero integer b.

6th Grade Arithmetic (with QuickTables)

Odd-Numbered Answers to Exercise Set 1.1: Numbers

Lesson 1: Arithmetic Review

CSc 372 Comparative Programming Languages

CSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. Department of Computer Science University of Arizona

Integers and Rational Numbers

Mini-Lesson 1. Section 1.1: Order of Operations PEMDAS

Number- Algebra. Problem solving Statistics Investigations

1. Download the JDK 6, from

Lecture Overview Code generation in milestone 2 o Code generation for array indexing o Some rational implementation Over Express Over o Creating

struct _Rational { int64_t Top; // numerator int64_t Bottom; // denominator }; typedef struct _Rational Rational;

Reteaching. Comparing and Ordering Integers

Course Learning Outcomes for Unit I. Reading Assignment. Unit Lesson. UNIT I STUDY GUIDE Number Theory and the Real Number System

Rational number operations can often be simplified by converting mixed numbers to improper fractions Add EXAMPLE:

1 Elementary number theory

Rational and Irrational Numbers

(3) Some memory that holds a value of a given type. (8) The basic unit of addressing in most computers.

MATHEMATICS Key Stage 2 Year 6

CS 455 Midterm Exam 1 Fall 2016 [Bono] Thursday, Sept. 29, 2016

CS 101 Fall 2006 Midterm 3 Name: ID:

Number Mulitplication and Number and Place Value Addition and Subtraction Division

Lesson 1: Arithmetic Review

Math Glossary Numbers and Arithmetic

CS3110 Spring 2017 Lecture 10 a Module for Rational Numbers

New Swannington Primary School 2014 Year 6

Java Identifiers, Data Types & Variables

JAVA OPERATORS GENERAL

Integers are whole numbers; they include negative whole numbers and zero. For example -7, 0, 18 are integers, 1.5 is not.


Name: Date: Review Packet: Unit 1 The Number System

Utilities (Part 2) Implementing static features

Learning Log Title: CHAPTER 3: ARITHMETIC PROPERTIES. Date: Lesson: Chapter 3: Arithmetic Properties

The Java language has a wide variety of modifiers, including the following:

Week 3: Functions and Data

Chapter 4 Section 2 Operations on Decimals

Imperative Languages!

Section A Arithmetic ( 5) Exercise A

Unit: Rational Number Lesson 3.1: What is a Rational Number? Objectives: Students will compare and order rational numbers.

User-built data types Mutable and immutable data

Chapter 1 An Introduction to Computer Science. INVITATION TO Computer Science 1

50 MATHCOUNTS LECTURES (6) OPERATIONS WITH DECIMALS

Fractions. Dividing the numerator and denominator by the highest common element (or number) in them, we get the fraction in its lowest form.

CSE 142 Su 04 Computer Programming 1 - Java. Objects

UCT Algorithm Circle: Number Theory

1.1 The Real Number System

Introduction to Programming in C Department of Computer Science and Engineering\ Lecture No. #02 Introduction: GCD

COMPSCI 105 S Principles of Computer Science. Classes 3

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Oral and Mental calculation

Fraction to Percents Change the fraction to a decimal (see above) and then change the decimal to a percent (see above).

Expected Standards for Year 6: Mathematics Curriculum (taken from ncetm progression maps)

ARITHMETIC EXPRESSION

Year 6 Term 1 and

Coding Standards for Java

COSC 243. Data Representation 3. Lecture 3 - Data Representation 3 1. COSC 243 (Computer Architecture)

Year 6 Maths Long Term Plan

A Fraction Class. Using a Fraction class, we can compute the above as: Assignment Objectives

Total 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Instructor: Final Exam Fall Section No.

5.5 Complex Fractions

Year 6.1- Number and Place Value 2 weeks- Autumn 1 Read, write, order and compare numbers up to and determine the value of each digit.

5.6 Rational Equations

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

CMSC 132, Object-Oriented Programming II Summer Lecture 1:

A.4 Rationalizing the Denominator

CSCE 110: Programming I

Slide 1 / 180. Radicals and Rational Exponents

Year 6 Mathematics Overview

Intro to Rational Expressions

Technical Section. Lab 4 while loops and for loops. A. while Loops or for loops

TACi: Three-Address Code Interpreter (version 1.0)

Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total.

EXAMPLE 1. Change each of the following fractions into decimals.

Number and Place Value

1.00 Lecture 4. Promotion

Objective A Identify the numerator and the denominator of a fraction. When the numerator is less than the denominator, it is a(n) fraction.

3.1 Dividing a Whole into Fractional Parts. 3.1 Dividing a Set into Fractional Parts. 3.2 Identifying Parts of Wholes.

Is the statement sufficient? If both x and y are odd, is xy odd? 1) xy 2 < 0. Odds & Evens. Positives & Negatives. Answer: Yes, xy is odd

Lecture 6. Drinking. Nested if. Nested if s reprise. The boolean data type. More complex selection statements: switch. Examples.

HOW TO DIVIDE: MCC6.NS.2 Fluently divide multi-digit numbers using the standard algorithm. WORD DEFINITION IN YOUR WORDS EXAMPLE

For Module 2 SKILLS CHECKLIST. Fraction Notation. George Hartas, MS. Educational Assistant for Mathematics Remediation MAT 025 Instructor

Y6 MATHEMATICS TERMLY PATHWAY NUMBER MEASURE GEOMETRY STATISTICS

Number System. Introduction. Natural Numbers (N) Whole Numbers (W) Integers (Z) Prime Numbers (P) Face Value. Place Value

A Proposal 1 to add the Infinite Precision Integer and Rational to the C ++ Standard Library

Transcription:

Lecture 13 Example Rational numbers: a number is rational if it can be defined as the ratio between two integers Issues in object-oriented programming The class Rational completed Material from Holmes Chapter 7: sections 1 through to 4, except section 6 (nothing explicitly about this in Hubbard), the ratio of the length of a circle circumference to its diameter, is a classical example of non-rational number Note that is also equal to 1 3 A class for the rational numbers class Rational { Encapsulation [Rumbaugh] Encapsulation (or information hiding) consists of separating the external aspects of an object, which are accessible to other objects, from the internal implementation details of the object, which are hidden from other objects // attributes private int numerator; private int denominator; // constructors public Rational () { numerator = 0; denominator = 1; public Rational ( int num, int denom) { numerator = num; denominator = denom; // reduces the fraction to its simplest form 2 3-1

Methods Revisited The variables numerator denominator are private to a rational number object They can only be accessed through methods defined in the class To display a rational number one should add a method similar to the following to the class Rational: public void printfraction () { if (denominator == 1) Systemoutprintln(numerator); else Systemoutprintln(numerator + "/" + denominator); Remarks Initial definitions: Rational a = new Rational(1,2); Rational b = new Rational(3,4); Rational c; Information hiding: the user only types cadd(a,b) doesn t need to know that a rational is implemented as a pair Inside the method: The use of xnumerator it is fine inside the class Outside the class there should not be any reference to the class private attributes this identifies the object itself It may be needed when the method has to return an object of the same type 4 6 To add two rationals to produce another rational we follow the rule then simplify the result Object Properties Since objects are stored by reference equality assignment operations need to be hled with some care If a b are two objects in the same class a = b a == b only deal with the object pointers not with their values // Equality between the given rational another one public Rational add ( Rational x, Rational y) { numerator = xnumerator * ydenominator + ynumerator * xdenominator; denominator = xdenominator * ydenominator; <=== reference to the object itself! public boolean equals ( Rational x ) { return (( thisnumerator == xnumerator ) && ( thisdenominator == xdenominator)); Rational a, b = new Rational( 2, 3 ); a = b; 5 7

// Copying objects Rational a, b = new Rational( 2, 3 ); a = b; // This only sets the pointers! // Damaging side effect: // changes to b imply chnges to a! public Rational copy () { Rational x = new Rational ( thisnumerator, thisdenominator ); return x; a = bcopy(); Class analysis The external structure of the class Rational is described below class Rational { // attributes private int numerator; private int denominator; // constructors public Rational (); public Rational ( int num, int denum ); // methods public Rational add ( Rational x, Rational y ); public Rational subtract ( Rational x, Rational y ); public Rational multiply ( Rational x, Rational y ); public Rational divide ( Rational x, Rational y ); public void printfraction (); public boolean equals ( Rational x ); public Rational copy (); Rational numerator denominator add ( Rationalx, Rational y) subtract ( Rational x, Rational y) multiply ( Rational x, Rational y) divide ( Rational x, Rational y) printfraction () equals copy () 8 10 Case Study: Arithmetic of Rational Numbers Problem Devise a Java class for the rational numbers Define methods to perform the four arithmetic operations on two rational numbers Also, define methods to print a rational number, copy a rational number compare two numbers for equality Problem analysis The operations on rationals are defined as follows: Algorithm Design Most of the methods above have already been implemented We just need to add some pseudo-code for a gcd algorithm for makerational Rationals should be expressed in minimal form A rational is reduced in minimal form by finding gcd dividing but by this number We ll call makerational this function 9 11

Example Euclid GCD algorithm Let, This is probably the oldest algorithm ever http://wwwcut-the-knotcom/blue/euclidhtml It is described as the solution to Proposition VII2 in Euclid s Elements: http://aleph0clarkuedu/ djoyce/java/elements/tochtml Given two numbers not prime to one another, to find their greatest common measure 2322 = 654*3 + 360 gcd 654 = 360*1 + 294 gcd 360 = 294*1 + 66 gcd 294 = 66*4 + 30 gcd 66 = 30*2 + 6 gcd 30 = 6*5 gcd gcd gcd gcd gcd gcd Therefore, gcd 12 14 Problem Analysis The algorithm is based on the following two observations: 1 If then gcd This is indeed so because no number (, in particular) may have a divisor greater than the number itself (I am talking here of non-negative integers) 2 If, for integers, then gcd gcd Indeed, every common divisor of a b also divides r Thus gcd divides gcd is a common divisor of hence gcd gcd The reverse is also true because every divisor of also divides But, of course, gcd Therefore, Algorithm for the greatest common divisor 1 divideby find remainder 2 while remainder is not zero 3 assign to 4 assign remainder to 5 divideby find remainder 6 assign to gcd 13 15

Algorithm for minimising a rational number 1 calculate gcd for a given 2 divide by gcd 3 divide by gcd 4 if either is zero 5 assign to 6 else 7 calculate the gcd for absolute values of 8 if 9 divide by gcd 10 divide by gcd 11 else 12 divide by negative gcd 13 divide by negative gcd or private void makerational() { int gcd; int divisor = 0; gcd = greatestcommondivisor(numerator, denominator); numerator = numerator / gcd; denominator = denominator / gcd; if (numerator == 0 denominator == 0) denominator = Mathabs(denominator); else { divisor = greatestcommondivisor(mathabs(numerator), Mathabs(denominator)); if (denominator > 0) { numerator = numerator / divisor; denominator = denominator / divisor; else { numerator = numerator / (-divisor); denominator = denominator / (-divisor); 16 16-2 // chap_7\ex_1java // program to test the methods of the rational class import javaio*; class Rational { private int numerator; private int denominator; // private methods, not to be seen from the outside private int greatestcommondivisor(int n, int d) { int remainder = n % d; while (remainder!= 0) { n = d; d = remainder; remainder = n % d; return d; // constructors public Rational() { numerator = 0; denominator = 1; public Rational(int num, int denom) { numerator = num; denominator = denom; // methods public Rational add(rational x, Rational y)d { numerator = xnumerator * ydenominator + ynumerator * xdenominator; denominator = xdenominator * ydenominator; 16-1 16-3

public Rational subtract(rational x, Rational y) { numerator = xnumerator * ydenominator - ynumerator * xdenominator; denominator = xdenominator * ydenominator; public Rational multiply(rational x, Rational y) { numerator = xnumerator * ynumerator; denominator = xdenominator * ydenominator; public Rational divide(rational x, Rational y) { numerator = xnumerator * ydenominator; denominator = xdenominator * ynumerator; class Ex_1 { public static void main(string[] args) throws IOException { Rational a = new Rational(-8,3); Rational b = new Rational(9,4); Rational c = new Rational(); Rational d; Systemoutprint("a="); aprintfraction(); Systemoutprint("b="); bprintfraction(); Systemoutprint("a+b="); cadd(a,b)printfraction(); Systemoutprint("a-b="); csubtract(a,b)printfraction(); Systemoutprint("a*b="); cmultiply(a,b)printfraction(); Systemoutprint("a/b="); cdivide(a,b)printfraction(); d=acopy(); Systemoutprint("d="); dprintfraction(); if (dequals(a)) Systemoutprintln("Both d a are equal"); 16-4 16-6 public void printfraction() { if (denominator == 1) Systemoutprintln(numerator); else Systemoutprintln(numerator + "/" + denominator); public boolean equals(rational x) { return ((thisnumerator == xnumerator) && (thisdenominator == xdenominator)); public Rational copy() { Rational temporary = new Rational(thisnumerator, thisdenominator); return temporary; Exercises 1 Draw a class diagram for the code in the example above 2 Extend the class Rational by implementing a between two rational numbers relation 3 To improve the accuracy of the numerical calculation involved replace int with long This should be transparent to the user 4 Repeat similar construction for complex numbers This is exercise 36 on page 276 16-5 17