Finding Pi: Applications of Loops, Random Numbers, Booleans CS 8: Introduction to Computer Science, Winter 2018 Lecture #6

Similar documents
Python, Part 2 CS 8: Introduction to Computer Science Lecture #4

Basic Data Types and Operators CS 8: Introduction to Computer Science, Winter 2019 Lecture #2

Professor Stephen Sekula

Monte Carlo Techniques. Professor Stephen Sekula Guest Lecture PHY 4321/7305 Sep. 3, 2014

More Examples Using Functions and Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #6

1. Practice the use of the C ++ repetition constructs of for, while, and do-while. 2. Use computer-generated random numbers.

More on Lists, Dictionaries Introduction to File I/O CS 8: Introduction to Computer Science Lecture #10

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

Review for the Final Exam CS 8: Introduction to Computer Science, Winter 2018 Lecture #15

61A Lecture 3. Friday, September 5

Strings in Python 1 Midterm#1 Exam Review CS 8: Introduction to Computer Science Lecture #6

(More) Fun with Pointers and Linked Lists! CS 16: Solving Problems with Computers I Lecture #17

File I/O in Python CS 8: Introduction to Computer Science Lecture #11

61A Lecture 4. Monday, September 9

Strings in Python: Cipher Applications CS 8: Introduction to Computer Science, Winter 2018 Lecture #9

Visual Basic for Applications

61A LECTURE 1 FUNCTIONS, VALUES. Steven Tang and Eric Tzeng June 24, 2013

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

More Examples Using Lists Tuples and Dictionaries in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #11

More on Arrays CS 16: Solving Problems with Computers I Lecture #13

Expressions and Variables

UNIT 3 CIRCLES AND VOLUME Lesson 5: Explaining and Applying Area and Volume Formulas Instruction

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Design and Debug: Essen.al Concepts CS 16: Solving Problems with Computers I Lecture #8

Variable and Data Type 2

Strings in Python: Cipher Applications CS 8: Introduction to Computer Science Lecture #7

Pre- Defined Func-ons in C++ Review for Midterm #1

File I/O in Python Formats for Outputs CS 8: Introduction to Computer Science, Winter 2018 Lecture #12

CS 101: Computer Programming and Utilization. Abhiram Ranade

Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7

MAT137 Calculus! Lecture 31

SAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik

Binary Arithmetic CS 64: Computer Organization and Design Logic Lecture #2

Efficacy of Numerically Approximating Pi with an N-sided Polygon

11.4 CIRCUMFERENCE AND ARC LENGTH 11.5 AREA OF A CIRCLE & SECTORS

CS 2316 Individual Homework 1 Python Practice Due: Wednesday, January 20 th, before 11:55 PM Out of 100 points

Welcome to Solving Problems with Computers I

Chapter 1: Symmetry and Surface Area

Functions and Libraries Once upon a time...

Math 1 Plane Geometry Part 1

Call-by-Type Functions in C++ Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #5

MIPS Assembly: More about MIPS Instructions Using Functions in MIPS CS 64: Computer Organization and Design Logic Lecture #8

Question 2. [5 points] Given the following symbolic constant definition

Outline. Announcements. Homework 2. Boolean expressions 10/12/2007. Announcements Homework 2 questions. Boolean expression

Math 2 Plane Geometry part 1 Unit Updated January 13, 2017

Moore Catholic High School Math Department

Dynamic Arrays Makefiles and Mul3ple File Compiles

Binary Arithmetic CS 64: Computer Organization and Design Logic Lecture #2 Fall 2018

Appendix E. Plane Geometry

CS 100: Programming Assignment P1

Python Lists and Dictionaries CS 8: Introduction to Computer Science, Winter 2019 Lecture #13

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

You know that the circumference of a specific circle divided by its diameter is the ratio pi, written as.

6.S189 Homework 2. What to turn in. Exercise 3.1 Defining A Function. Exercise 3.2 Math Module.

Iteration and For Loops

You will need the following items: scissors, plate, 5 different colored pencils, protractor, paper to answer questions

Middle School Summer Review Packet for Abbott and Orchard Lake Middle School Grade 7

Middle School Summer Review Packet for Abbott and Orchard Lake Middle School Grade 7

The float type and more on variables FEB 6 TH 2012

CpSc 1111 Lab 6 Conditional Statements, Loops, the Math Library, and Random Numbers What s the Point?

Mathematics Scope & Sequence Grade 8 Revised: June 2015

List Comprehensions and Simulations

MIPS Instruc,ons CS 64: Computer Organiza,on and Design Logic Lecture #8

Unit 10: Data Structures CS 101, Fall 2018

Moore Catholic High School Math Department

Day 5: Inscribing and Circumscribing Getting Closer to π: Inscribing and Circumscribing Polygons - Archimedes Method. Goals:

Object-Based Programming. Programming with Objects

Circumference of a Circle

SF - Math Steps, MI test, other review MATH INVENTORY. Week 3-8/28-9/1 - Standards: Lesson Objective/Plan Resources Section in Book Homework

Binary Arithme-c 2 Intro to Assembly CS 64: Computer Organiza-on and Design Logic Lecture #3

Key Vocabulary Index. Key Vocabulary Index

CS 2316 Individual Homework 1 Python Practice Due: Wednesday, August 28th, before 11:55 PM Out of 100 points

2 nd Semester Geometry Review Packet. In the diagram, ABCDE ~ FGHJK. 1) Find the value of x. 2) Find the perimeter of ABCDE.

Eighth Grade Math Assessment Framework Standard 6A Representations and Ordering

Geometry: Angle Relationships

Overloading Functions & Command Line Use in C++ CS 16: Solving Problems with Computers I Lecture #6

Python Programming Exercises 1

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

Tier 2: GEOMETRY INTRODUCTION TO GEOMETRY Lessons Abbreviation Key Table... 7 G1 LESSON: WHAT IS GEOMETRY?... 8 G1E... 9 G1EA...

Math 7 Glossary Terms

Unit 1 Lesson 4. Introduction to Control Statements

Test #2 October 8, 2015

Functions with Parameters and Return Values

Mathematics: working hard together, achieving together, making every lesson count

An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s.

CMPSCI 250: Introduction to Computation. Lecture #1: Things, Sets and Strings David Mix Barrington 22 January 2014

Chapter 1: Number and Operations

Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10

S206E Lecture 13, 5/22/2016, Grasshopper Math and Logic Rules

Math Circle Intermediate Group October 30, 2016 Geometric Probability

CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, Good Luck!

UNIT 3 - MEASUREMENT & PROPORTIONAL REASONING TEST

CS 1803 Individual Homework 1 Python Practice Due: Wednesday, January 26th, before 6 PM Out of 100 points

61A Lecture 6. Monday, February 2

Area and Volume 1. Circumference and Area of a Circle. Area of a Trapezium. and Measures. Geometry. Key Point. Key Point.

Expressions in JavaScript. Jerry Cain CS 106AJ October 2, 2017

61A Lecture 7. Monday, September 15

Com S 127 Lab 2. For the first two parts of the lab, start up Wing 101 and use the Python shell window to try everything out.

Compiling C++ Programs Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Math 451: Euclidean and Non-Euclidean Geometry MWF 3pm, Gasson 204 Homework 8 Solutions

Transcription:

Finding Pi: Applications of Loops, Random Numbers, Booleans CS 8: Introduction to Computer Science, Winter 2018 Lecture #6 Ziad Matni Dept. of Computer Science, UCSB

Administrative New Homework (#3) is online due next Monday New Lab (#2) this week The grader, Vivek Pradhan, will hold office hours on Thursdays from 3pm to 4pm in the CSIL lab Midterm is on Wednesday, Feb 14 th 2/5/18 Matni, CS8, Wi18 2

Lecture Outline More Loops with Mathematical Applications Looking for Pi in all the Right Places Characters and Strings in Python 2/5/18 Matni, CS8, Wi18 3

Class Exercise Get together with 2 or 3 other people around you and answer this question. You can use your notes from other lectures: Write Python code that asks a user for a number between 0 and 200 (inclusive). Call that variable SideParam. Then it asks the user for another number between 3 and 360 (inclusive). Call that variable Sides. a) The code should first check that the 2 input numbers do indeed meet this criteria. Bonus points if you can do this with ONE if-statement! If any of the criteria is not met, you should print a message to say it was out of range and stop. b) Then, have your code use the Turtle graphics module to draw a polygon with number of sides equal to Sides and having side lengths to half of SideParam, plus 50. 2/5/18 Matni, CS8, Wi18 4

An Ancient Problem: Finding π Ratio of a circle s circumference to its diameter π = circumference / diameter # for any circle Irrational number: an infinite series of non-repeating digits So it can never be represented exactly, only approximated Chapter 2 explores various ways to approximate pi But just to teach problem-solving. For calculating, use math.pi module import math # necessary to use math module area = math.pi * radius * radius By the way, the math module has lots of other cool stuff Square root, trig functions, e, for more info on IDLE, try >>> help(math) 2/5/18 Matni, CS8, Wi18 5

The math Library Must be import-ed Contains lots of often-used mathematical functions, like: math.fabs(x) # Returns the absolute value of x math.exp(x) # Returns e**x math.pow(x,y) # Returns x**y math.sqrt(x) # Returns the square-root of x math.log(x, b) # Returns the log of x, base b math.sin(x) or.cos(x) or.tan(x) # Trig functions math.pi # Returns pi (3.141 ) math.e # Returns e (2.718 ) See https://docs.python.org/2/library/math.html for full details CLASS DEMO 2/5/18 Matni, CS8, Wi18 6

Accumulator Pattern We can calculate PI using summing infinite series General idea applies to counting, summing, Idea: set initial value, then loop to update a running sum e.g., add numbers 1 through 5: sum = 0 # initialize sum (accumulator variable) for number in range(1, 6): sum = sum + number # updates sum See textbook for 2 different ways to find pi: Leibniz Formula summation of terms (p.58) --- ACCUMULATED SUM Wallis Formula product of terms (p. 60) --- ACCUMULATED PRODUCT 2/5/18 7

Liebniz Formula So, the formula suggests that: π = 4. { Σ (-1) n. [1 / (2n + 1)] } as n goes from 0 à When n = 0, π est = 4. (1) = 4 When n = 1, π est = 4. (1 1/3) = 8/3 = 2.66667 When n = 2, π est = 4. (1 1/3 + 1/5) = 3.46667 When n = 100, π est = 4. (1 1/3 + 1/5 + + 1/201) = 3.13159 2/5/18 CLASS DEMO: HOW Matni, CS8, Wi18 TO CODE THIS! 8

Accumulated Product Example: How would you create a function that takes a positive integer N and returns the product of all numbers less than or equal to N? In other words: Product(N) = 1 x 2 x 3 x N Example: Product(3) = 6, Product(4) = 24, etc 2/5/18 CLASS DEMO: HOW Matni, CS8, Wi18 TO CODE THIS! 9

Random Values Must be import-ed Pseudo-random values can be generated using special functions in most programming languages In Python use functions of the random module Simplest is random.random() returns a floating point value between 0.0 and 1.0 Also randrange(n), randint(low, high), shuffle(list) and many others Try help(random) to learn more and play around with it For example, Listing 2.5 uses random() for x, y dart locations 2/5/18 CLASS DEMO: HOW Matni, CS8, Wi18 TO USE random 10

Monte Carlo Simulation A popular statistical method using randomness to solve problems. Used in many simulation traffic flows, length of bank queues, etc In the case of estimating pi imagine throwing darts at a unit circle (i.e. r = 1) inscribed inside a square (i.e. whose side = 2r = 2) Circle area = πr² = π Square area = 2 * 2 = 4 So if n darts hit the square, how many darts (k) should land inside the circle by chance alone? As it turns out, that s proportional to the area of the circle divided by the area of the square. Answer: k = n * π/4. In other words, we can approximate π est = 4 * k/n See Listing 2.5 in textbook 2/5/18 CLASS DEMO: HOW Matni, CS8, Wi18 TO USE random 11

montepi(numdarts) def montepi(numdarts): # numdarts is the number of darts that we throw at the square k = 0 # k is the nuber of darts that hit the circle inside the square for i in range(numdarts): x = random.random() # x and y are random coordinates y = random.random() # representing the dart throw location d = math.sqrt(x**2 + y**2) # d = distance between (x,y) and origin (0,0) if d <= 1: # if d <= 1, it means that the k = k + 1 # hit is within the circle, so count those pi = 4 * (k /numdarts) return pi QUESTION: How close do we get to actual π using this method? (see demo from class ) 2/5/18 Matni, CS8, Wi18 12

Boolean Expressions Expressions that evaluate to True or False Relational operators: < <= > >= ==!= Example: 9 > 7 is True, while (4.5 3) >= (3 1.3) is False Watch out when using == or!= with floating point numbers Example: 100/3 == 33.3333 False (why?) Instead it s better to compare absolute difference to a small value abs(100/3-33.3333) < 0.0001 True (why?) 2/5/18 Matni, CS8, Wi18 13

Compound Boolean Expressions Logical operators: and, or, not Their operands are Boolean values: True and False 7 < 9 and 100 > 10 400 / 10 == 92 or 8 > 3 not 6 > 150 False True True True Special Python feature: low <= value <= high The special role that 0 and 1 play See other behavior notes in Table 2.2 (p. 66) 2/5/18 Matni, CS8, Wi18 14

YOUR TO-DOs q Finish reading Chapters 2 and 3 for next class q Finish Homework3 (due Monday 2/12) q Finish Lab2 (due Wednesday 2/7) q Run through an open meadow 2/5/18 Matni, CS8, Wi18 15

2/5/18 Matni, CS8, Wi18 16