CS 115 Lecture 5 Math library; building a project Taken from notes by Dr. Neil Moore.

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

A number of MATLAB statements that allow us to control the order in which statements are executed in a program. There are two broad categories of control.
Computer Programming w/ Eng. Applications
Python Programming: An Introduction to Computer Science
Vahé Karamian Python Programming CS-110 CHAPTER 2 Writing Simple Programs.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Python November 14, Unit 7. Python Hello world, in class.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
CS 201 Functions Debzani Deb.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
Computer Science 101 Introduction to Programming.
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers.
Python.
Computer Science 1000 Spreadsheets II Permission to redistribute these slides is strictly prohibited without permission.
19/5/2015CS150 Introduction to Computer Science 1 Announcements  1st Assignment due next Monday, Sep 15, 2003  1st Exam next Friday, Sep 19, 2003  1st.
Vahé Karamian Python Programming CS-110 CHAPTER 3 Computing with Numbers.
Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
A First Program CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Credits: a significant part of.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
FUNCTIONS. Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Computer Science 101 Introduction to Programming.
Chapter 3.  Traditionally, programming languages have assigned different types of data for different types of numbers.  In many languages, there may.
Numeric Types, Expressions, and Output ROBERT REAVES.
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
D-1 University of Washington Computer Programming I Lecture 4: Arithmetic Expressions © 2000 UW CSE.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 2 Input,
Input, Output, and Processing
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 2.
Computer Science 101 Introduction to Programming.
Arithmetic Operators Topics Arithmetic Operators Operator Precedence
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
Agenda Review C++ Library Functions Review User Input Making your own functions Exam #1 Next Week Reading: Chapter 3.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
COSC 1306—COMPUTER SCIENCE AND PROGRAMMING PYTHON FUNCTIONS Jehan-François Pâris
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Variables Damian Gordon. Variables We know what a variable is from maths. We’ve all seen this sort of thing in algebra: 2x – 10 = 0 2x = 10 X = 5.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
CSC Programming I Lecture 6 September 4, 2002.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 5 JavaScript.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
A First Program CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Credits: a significant part of.
2. WRITING SIMPLE PROGRAMS Rocky K. C. Chang September 10, 2015 (Adapted from John Zelle’s slides)
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
Today in CS161 Lecture #5 Learn about… Data types (char, int, float) Input and Output (cin, cout) Writing our First Program Write the Inches to MM Program.
D-1 University of Washington Computer Programming I Lecture 4: Arithmetic Expressions © 2000 UW CSE.
29 January 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Review: A Structural View program modules -> main program -> functions -> libraries statements -> simple statements -> compound statements expressions.
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
Fundamentals of Programming I Overview of Programming
CMPT 120 Topic: Python’s building blocks -> More Statements
Topics Designing a Program Input, Processing, and Output
Introduction To Repetition The for loop
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Functions Taken from notes by Dr. Neil Moore
Conditions and Ifs BIS1523 – Lecture 8.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Terminal-Based Programs
Unit 3: Variables in Java
CISC101 Reminders Assignment 3 due today.
Functions Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Presentation transcript:

CS 115 Lecture 5 Math library; building a project Taken from notes by Dr. Neil Moore

The math library We’ve seen how to do everything a five-function calculator can do. What about more advanced math? That’s available in Python too. But it’s not built-in like + and float are. Instead it’s in a library. – A collection of pre-written code intended to be re-used. Functions Constants Types (“classes”) – The math library comes with Python. – graphics (chapter 3) is a third-party library. The Python math library has: – Functions for trigonometry, logarithms, and more. – Constants like π and e.

Using libraries in Python To use a library, you must first import it. import math – Put this at the very top of the program – After header comments, before “def main():” Then your program can use the things in the library – Their names are library.name – So math.log (function) and math.pi (constant) – You call functions with parenthesized arguments Just like input and print – Each function has its own rules about what its arguments are, what they mean, how many there are, etc.

Using libraries in Python If the function returns a value, you use it as part of an expression height = math.log(size, 2) If it does not return a value, use it as an entire statement by itself: random.seed() Only import the libraries you need! – for documentation, for efficiency, for style

A variation on import You can instead import particular functions or constants specifically by writing import this way: from math import sin, cos, tan, pi – List the names that you are importing, separated by commas – Then you can use them without the “math.” y = sin(angle) * radius – Saves typing if you use a function many times

One last variation on import One last way to write import: from math import * – It imports everything in the library – And you don’t have to use “math.” num = e ** pi – Sounds great, right? There can be a catch… – What if next version of Python adds a new function which is the same name as one of your variables or functions? – Your code could break! And have to be rewritten! – Professional programmers avoid “from lib import *, because of this catch. In class we’ll use it occasionally

What’s in the math library

Common misunderstanding For some reason, once people know about the math library, they feel that they MUST import it for any kind of arithmetic, using +, -, *, /, //, **, %, etc. This is NOT the case. All these operators were available before you even knew about import, they are still available as being builtin to Python. You need to import math ONLY when you are using math library functions (sqrt, log, …) and constants (pi, e)

Rounding One more numeric function, builtin – so you do NOT have to import math library to use it round has either one or two arguments – If it has just ONE argument, it will round the argument to the nearest integer round(5.2) → 5 round (7.9) → 8 – If it has TWO arguments, the second one is the number of decimal places desired. The first argument’s value will be rounded to that number of decimals round (math.pi, 2) → 3.14 round ( , 0) → 3.0 round (12, -1) → 10

Rounding One more numeric function, builtin – so you do NOT have to import math library to use it round has either one or two arguments – If it has just ONE argument, it will round the argument to the nearest integer round(5.2) → 5 round (7.9) → 8 round (5.235) → 5 round (5.725) →6

Rounding One more numeric function, builtin – so you do NOT have to import math library to use it round has either one or two arguments – If it has TWO arguments, the second one is the number of decimal places desired. The first argument’s value will be rounded to that number of decimals round (math.pi, 2) → 3.14 round ( , 0) → 3.0 round (12, -1) → 10 Note that a value ending in 5 does not always round up! It rounds towards the even number – doc.python.org says that it is because of the problems with representing floating point numbers So that round(5.3545, 3) → (because 4 is even) And round(5.3555, 3) → (because 6 is even) And round(4.5) → 4, and round(5.5) → 6

The round function round(number[, ndigits]) Return the floating point value number rounded to ndigits digits after the decimal point. If ndigits is omitted, it returns the nearest integer to its input. For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). The return value is an integer if called with one argument, otherwise of the same type as number.round() The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.round()Floating Point Arithmetic: Issues and Limitations From: und

A complete program Let’s go through the whole process of making a (simple) program, from start to finish. The steps are: Specification (the “assignment”, usually given to you) Test plan Design (pseudocode, algorithm) Writing code Testing

Specification

Test plan What kind of inputs to test? Normal inputs: both integers and floats. Are there any boundary cases? – Not really for the formula Some people would argue for absolute zero ( degrees Fahrenheit or degrees Celsius) because of physics – Still we might test 0, should test negative numbers Other special cases? – If the input had more than one digit after decimal, to check for rounding correctly Any error cases? – Non-numeric input

Test plan DescriptionInputExpected output Normal, integer F is 0.0 C Normal, float F is 37.0 C Normal, zero F is C Normal, negative F is C Normal, absolute zero F is F Special, to check rounding F is C Error, non-numeric inputZeroTerminates with error message about wrong type

Design For the design, we start with the purpose, inputs (preconditions) and outputs (postconditions). Purpose: Convert a temperature from Fahrenheit to Celsius. Preconditions: User enters a temperature in Fahrenheit. Postconditions: Program prints the message “x F is y C.”, rounded to one digit after the decimal point.

Pseudocode

Pseudocode to comments Make each step into a comment. #Purpose: Convert a temperature from Fahrenheit to # Celsius. #Preconditions: User enters a temperature in Fahrenheit. #Postconditions: Program prints the message “x F is y C.”, # rounded to one digit after the decimal point. # 1. Get the Fahrenheit temperature from the user # 2. Convert to Celsius using the formula C = 5/9 (F – 32) # 3. Round the Fahrenheit temperature to one decimal. # 4. Round the Celsius temperature to one decimal. # 5. Output the answer message.

Writing the code Put the steps inside a def main(): and call the main function at the end. # Purpose: Convert a temperature from Fahrenheit to # Celsius. #Preconditions: User enters a temperature in Fahrenheit. #Postconditions: Program prints the message “x F is y C.”, # rounded to one digit after the decimal point. def main(): # 1. Get the Fahrenheit temperature from the user # 2. Convert to Celsius using the form. C = 5/9 (F – 32) # 3. Round the Fahrenheit temperature to one decimal. # 4. Round the Celsius temperature to one decimal. # 5. Output the answer message. main()

Writing the code And write code for each line of the design. def main(): # 1. Get the Fahrenheit temperature from the user fahr = float(input(“Enter a temp in Fahrenheit: “)) # 2. Convert to Celsius using the form. C = 5/9 (F – 32) celsius = (5/9) * (fahr – 32) # 3. Round the Fahrenheit temperature to one decimal. fahr_round = round(fahr, 1) # 4. Round the Celsius temperature to one decimal. cels_round = round(celsius, 1) # 5. Output the answer message. print(fahr_round, “F is”, cels_round, “C.”) main()

Testing Now run the program once for each test case. Give the input and verify that the output matches the expected output. If not, there is a bug: – Maybe in your program… – Maybe in your test case! After you fix a bug, repeat all the tests. – Regression testing!