Python Programming: An Introduction to Computer Science

Similar documents
CITS 1401 Problem Solving & Programming

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

Python Programming: An Introduction to Computer Science

Lecture Numbers. Richard E Sarkis CSC 161: The Art of Programming

Last Time. integer/float/string. import math math.sqrt() math.pi. Python Programming, 2/e 2

Comp 151. More on Arithmetic and intro to Objects

Writing Python Programs, Numerical Data Types

Comp 151. More on Arithmetic and number types

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

Computing with Numbers

" # # if $ " %&% # ifelse $ " #&% # ifelif-else $ +bool ##%# # #.* $ ## # .# *#%$ % ## % .#*#%*

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Classwork. Exercises Use long division to determine the decimal expansion of. NYS COMMON CORE MATHEMATICS CURRICULUM Lesson 6 8 7

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

CIS133J. Working with Numbers in Java

Multi-Way Decisions. The newest program is great, but it still has some quirks! This program finds the real solutions to a quadratic

Chapter 1. Math review. 1.1 Some sets

MA 1128: Lecture 02 1/22/2018

Table of Laplace Transforms

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

Solving Equations with Inverse Operations

Python Numbers. Learning Outcomes 9/19/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17

Expressions and Casting

Numerical Precision. Or, why my numbers aren t numbering right. 1 of 15

Divisibility Rules and Their Explanations

CGF Lecture 2 Numbers

Decision structures. A more complex decision structure is an if-else-statement: if <condition>: <body1> else: <body2>

Properties and Definitions

>>> * *(25**0.16) *10*(25**0.16)

Graphics calculator instructions

Natural Numbers and Integers. Big Ideas in Numerical Methods. Overflow. Real Numbers 29/07/2011. Taking some ideas from NM course a little further

Built-in Types of Data

Project 2: How Parentheses and the Order of Operations Impose Structure on Expressions

EC121 Mathematical Techniques A Revision Notes

File processing and decision structures

6.1 Evaluate Roots and Rational Exponents

Get to Know Your Calculator!

Basics of Computational Geometry

2.Simplification & Approximation

Helping Students Understand Pre-Algebra

MAT 003 Brian Killough s Instructor Notes Saint Leo University

Section 1.1 Definitions and Properties

Rational and Irrational Numbers

Rational Number is a number that can be written as a quotient of two integers. DECIMALS are special fractions whose denominators are powers of 10.

Chapter 1 Operations With Numbers

Unit 2: Accentuate the Negative Name:

Programming Project #2: Solving Quadratic Equations Date Due: Monday 25 September 2017

Intermediate Algebra. Gregg Waterman Oregon Institute of Technology

Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions. Grace Murray Hopper. Arithmetic Expressions.

Topic 2: Decimals. Topic 1 Integers. Topic 2 Decimals. Topic 3 Fractions. Topic 4 Ratios. Topic 5 Percentages. Topic 6 Algebra

Math Day 2 Programming: How to make computers do math for you

CS 115 Lecture 4. More Python; testing software. Neil Moore

Chapter 2. Data Representation in Computer Systems

2.1 Basics of Functions and Their Graphs

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

Outline. Data and Operations. Data Types. Integral Types

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Mathematical Data Operators

may be sent to:

CS321 Introduction To Numerical Methods

Modular Arithmetic. is just the set of remainders we can get when we divide integers by n

Mark Important Points in Margin. Significant Figures. Determine which digits in a number are significant.

Lecture 2: Python Arithmetic

3x - 5 = 22 4x - 12 = 2x - 9

Extended Introduction to Computer Science CS1001.py. Lecture 5 Part A: Integer Representation (in Binary and other bases)

BEGINNING PROBLEM-SOLVING CONCEPTS FOR THE COMPUTER. Chapter 2

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

Exponential Numbers ID1050 Quantitative & Qualitative Reasoning

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

Math 340 Fall 2014, Victor Matveev. Binary system, round-off errors, loss of significance, and double precision accuracy.

Floating-Point Data Representation and Manipulation 198:231 Introduction to Computer Organization Lecture 3

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

Multiply Decimals Multiply # s, Ignore Decimals, Count # of Decimals, Place in Product from right counting in to left

C++ Programming: From Problem Analysis to Program Design, Third Edition

Python Programming Exercises 1

Overview (4) CPE 101 mod/reusing slides from a UW course. Assignment Statement: Review. Why Study Expressions? D-1

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

Table of Contents. Introduction to the Math Practice Series...iv Common Mathematics Symbols and Terms...1

Math 7 Notes Unit Three: Applying Rational Numbers

Algorithms and Programming I. Lecture#12 Spring 2015

Object Oriented Programming Using C++ Mathematics & Computing IET, Katunayake

1.1 Review of Place Value

Skill 1: Multiplying Polynomials

Grade 6 Math Circles November 6 & Relations, Functions, and Morphisms

Data Types. Data Types. Integer Types. Signed Integers

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Mathematical preliminaries and error analysis

Numerical computing. How computers store real numbers and the problems that result

Transcription:

Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers Python Programming, 2/e 1

Objectives n To understand the concept of data types. n To be familiar with the basic numeric data types in Python. n To understand the fundamental principles of how numbers are represented on a computer. Python Programming, 2/e 2

Objectives (cont.) n To be able to use the Python math library. n To understand the accumulator program pattern. n To be able to read and write programs that process numerical data. Python Programming, 2/e 3

Numeric Data Types n The information that is stored and manipulated bu computers programs is referred to as data. n There are two different kinds of numbers! n (5, 4, 3, 6) are whole numbers they don t have a fractional part n (.25,.10,.05,.01) are decimal fractions Python Programming, 2/e 4

Numeric Data Types n Inside the computer, whole numbers and decimal fractions are represented quite differently! n We say that decimal fractions and whole numbers are two different data types. n The data type of an object determines what values it can have and what operations can be performed on it. Python Programming, 2/e 5

Numeric Data Types n Whole numbers are represented using the integer (int for short) data type. n These values can be positive or negative whole numbers. Python Programming, 2/e 6

Numeric Data Types n Numbers that can have fractional parts are represented as floating point (or float) values. n How can we tell which is which? n A numeric literal without a decimal point produces an int value n A literal that has a decimal point is represented by a float (even if the fractional part is 0) Python Programming, 2/e 7

Numeric Data Types n Python has a special function to tell us the data type of any value. >>> type(3) <class 'int'> >>> type(3.1) <class 'float'> >>> type(3.0) <class 'float'> >>> myint = 32 >>> type(myint) <class 'int'> >>> Python Programming, 2/e 8

Numeric Data Types n Why do we need two number types? n n n n Values that represent counts can t be fractional (you can t have 3 ½ quarters) Most mathematical algorithms are very efficient with integers The float type stores only an approximation to the real number being represented! Since floats aren t exact, use an int whenever possible! Python Programming, 2/e 9

Numeric Data Types n Operations on ints produce ints, operations on floats produce floats (except for /). >>> 3.0+4.0 7.0 >>> 3+4 7 >>> 3.0*4.0 12.0 >>> 3*4 12 >>> 10.0/3.0 3.3333333333333335 >>> 10/3 3.3333333333333335 >>> 10 // 3 3 >>> 10.0 // 3.0 3.0 Python Programming, 2/e 10

Numeric Data Types n Integer division produces a whole number. n That s why 10//3 = 3! n Think of it as gozinta, where 10//3 = 3 since 3 gozinta (goes into) 10 3 times (with a remainder of 1) n 10%3 = 1 is the remainder of the integer division of 10 by 3. n a = (a/b)(b) + (a%b) Python Programming, 2/e 11

Using the Math Library n Besides (+, -, *, /, //, **, %, abs), we have lots of other math functions available in a math library. n A library is a module with some useful definitions/functions. Python Programming, 2/e 12

Using the Math Library n Let s write a program to compute the roots of a quadratic equation! x = - ± - 2a 2 b b 4ac n The only part of this we don t know how to do is find a square root but it s in the math library! Python Programming, 2/e 13

Using the Math Library n To use a library, we need to make sure this line is in our program: import math n Importing a library makes whatever functions are defined within it available to the program. Python Programming, 2/e 14

Using the Math Library n To access the sqrt library routine, we need to access it as math.sqrt(x). n Using this dot notation tells Python to use the sqrt function found in the math library module. n To calculate the root, you can do discroot = math.sqrt(b*b 4*a*c) Python Programming, 2/e 15

Using the Math Library # quadratic.py # A program that computes the real roots of a quadratic equation. # Illustrates use of the math library. # Note: This program crashes if the equation has no real roots. import math # Makes the math library available. def main(): print("this program finds the real solutions to a quadratic") print() a, b, c = eval(input("please enter the coefficients (a, b, c): ")) discroot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discroot) / (2 * a) root2 = (-b - discroot) / (2 * a) print() print("the solutions are:", root1, root2 ) main() Python Programming, 2/e 16

Using the Math Library This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 3, 4, -1 The solutions are: 0.215250437022-1.54858377035 n What do you suppose this means? This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 1, 2, 3 Traceback (most recent call last): File "<pyshell#26>", line 1, in -toplevelmain() File "C:\Documents and Settings\Terry\My Documents\Teaching\W04\CS 120\Textbook\code\chapter3\quadratic.py", line 14, in main discroot = math.sqrt(b * b - 4 * a * c) ValueError: math domain error >>> Python Programming, 2/e 17

Math Library n If a = 1, b = 2, c = 3, then we are trying to take the square root of a negative number! n Using the sqrt function is more efficient than using **. How could you use ** to calculate a square root? Python Programming, 2/e 18

Accumulating Results: Factorial n Say you are waiting in a line with five other people. How many ways are there to arrange the six people? n 720 -- 720 is the factorial of 6 (abbreviated 6!) n Factorial is defined as: n! = n(n-1)(n-2) (1) n So, 6! = 6*5*4*3*2*1 = 720 Python Programming, 2/e 19

Accumulating Results: Factorial n How we could we write a program to do this? n Input number to take factorial of, n Compute factorial of n, fact Output fact Python Programming, 2/e 20

Accumulating Results: Factorial n How did we calculate 6!? n 6*5 = 30 n Take that 30, and 30 * 4 = 120 n Take that 120, and 120 * 3 = 360 n Take that 360, and 360 * 2 = 720 n Take that 720, and 720 * 1 = 720 Python Programming, 2/e 21

Accumulating Results: Factorial n n n What s really going on? We re doing repeated multiplications, and we re keeping track of the running product. This algorithm is known as an accumulator, because we re building up or accumulating the answer in a variable, known as the accumulator variable. Python Programming, 2/e 22

Accumulating Results: Factorial n The general form of an accumulator algorithm looks like this: Initialize the accumulator variable Loop until final result is reached update the value of accumulator variable Python Programming, 2/e 23

Accumulating Results: Factorial n It looks like we ll need a loop! fact = 1 for factor in [6, 5, 4, 3, 2, 1]: fact = fact * factor n Let s trace through it to verify that this works! Python Programming, 2/e 24

Accumulating Results: Factorial n Why did we need to initialize fact to 1? There are a couple reasons n Each time through the loop, the previous value of fact is used to calculate the next value of fact. By doing the initialization, you know fact will have a value the first time through. n If you use fact without assigning it a value, what does Python do? Python Programming, 2/e 25

Accumulating Results: Factorial n Since multiplication is associative and commutative, we can rewrite our program as: fact = 1 for factor in [2, 3, 4, 5, 6]: fact = fact * factor n Great! But what if we want to find the factorial of some other number?? Python Programming, 2/e 26

Accumulating Results: Factorial n What does range(n) return? 0, 1, 2, 3,, n-1 n range has another optional parameter! range(start, n) returns start, start + 1,, n-1 n But wait! There s more! range(start, n, step) start, start+step,, n-1 n list(<sequence>) to make a list Python Programming, 2/e 27

Accumulating Results: Factorial n Let s try some examples! >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(range(5,10)) [5, 6, 7, 8, 9] >>> list(range(5,10,2)) [5, 7, 9] Python Programming, 2/e 28

Accumulating Results: Factorial n Using this souped-up range statement, we can do the range for our loop a couple different ways. n We can count up from 2 to n: range(2, n+1) (Why did we have to use n+1?) n We can count down from n to 2: range(n, 1, -1) Python Programming, 2/e 29

Accumulating Results: Factorial n Our completed factorial program: # factorial.py # Program to compute the factorial of a number # Illustrates for loop with an accumulator def main(): n = eval(input("please enter a whole number: ")) fact = 1 for factor in range(n,1,-1): fact = fact * factor print("the factorial of", n, "is", fact) main() Python Programming, 2/e 30

The Limits of Int n What is 100!? >>> main() Please enter a whole number: 100 The factorial of 100 is 9332621544394415268169923885626670049071596826438162 1468592963895217599993229915608941463976156518286253 6979208272237582511852109168640000000000000000000000 00 n Wow! That s a pretty big number! Python Programming, 2/e 31

The Limits of Int n Newer versions of Python can handle it, but Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> import fact >>> fact.main() Please enter a whole number: 13 13 12 11 10 9 8 7 6 5 4 Traceback (innermost last): File "<pyshell#1>", line 1, in? fact.main() File "C:\PROGRA~1\PYTHON~1.2\fact.py", line 5, in main fact=fact*factor OverflowError: integer multiplication Python Programming, 2/e 32

The Limits of Int n What s going on? n While there are an infinite number of integers, there is a finite range of ints that can be represented. n This range depends on the number of bits a particular CPU uses to represent an integer value. Typical PCs use 32 bits. Python Programming, 2/e 33

The Limits of Int n Typical PCs use 32 bits n That means there are 2 32 possible values, centered at 0. n This range then is 2 31 to 2 31-1. We need to subtract one from the top end to account for 0. n But our 100! is much larger than this. How does it work? Python Programming, 2/e 34

Handling Large Numbers n Does switching to float data types get us around the limitations of ints? n If we initialize the accumulator to 1.0, we get >>> main() Please enter a whole number: 15 The factorial of 15 is 1.307674368e+012 n We no longer get an exact answer! Python Programming, 2/e 35

Handling Large Numbers: Long Int n Very large and very small numbers are expressed in scientific or exponential notation. n 1.307674368e+012 means 1.307674368 * 10 12 n Here the decimal needs to be moved right 12 decimal places to get the original number, but there are only 9 digits, so 3 digits of precision have been lost. Python Programming, 2/e 36

Handling Large Numbers n Floats are approximations n Floats allow us to represent a larger range of values, but with lower precision. n Python has a solution, expanding ints! n Python Ints are not a fixed size and expand to handle whatever value it holds. Python Programming, 2/e 37

Handling Large Numbers n n Newer versions of Python automatically convert your ints to expanded form when they grow so large as to overflow. We get indefinitely large values (e.g. 100!) at the cost of speed and memory Python Programming, 2/e 38

Type Conversions n We know that combining an int with an int produces an int, and combining a float with a float produces a float. n What happens when you mix an int and float in an expression? x = 5.0 + 2 n What do you think should happen? Python Programming, 2/e 39

Type Conversions n For Python to evaluate this expression, it must either convert 5.0 to 5 and do an integer addition, or convert 2 to 2.0 and do a floating point addition. n Converting a float to an int will lose information n Ints can be converted to floats by adding.0 Python Programming, 2/e 40

Type Conversion n In mixed-typed expressions Python will convert ints to floats. n Sometimes we want to control the type conversion. This is called explicit typing. Python Programming, 2/e 41

Type Conversions >>> float(22//5) 4.0 >>> int(4.5) 4 >>> int(3.9) 3 >>> round(3.9) 4 >>> round(3) 3 Python Programming, 2/e 42