CS 1000 H. James de St. Germain Problem Solving Writing a Program to Approximate Pi (or why 3.141592653589793238462643383279502884197169399 is better than.

Slides:



Advertisements
Similar presentations
Mr F’s Maths Notes Number 11. Standard Form.
Advertisements

Writing Pseudocode And Making a Flow Chart A Number Guessing Game
The Game of Algebra or The Other Side of Arithmetic The Game of Algebra or The Other Side of Arithmetic © 2007 Herbert I. Gross by Herbert I. Gross & Richard.
Summer 2012 Instructor: Hassan Khosravi
While loops.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Decisions If statements in C.
Sorting It All Out Mathematical Topics
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.
An Interactive Tutorial by S. Mahaffey (Osborne High School)
Python Basics: Statements Expressions Loops Strings Functions.
Order of Operations And Real Number Operations
L6:CSC © Dr. Basheer M. Nasef Lecture #6 By Dr. Basheer M. Nasef.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Loops.
Programing Concept Ken Youssefi/Ping HsuIntroduction to Engineering – E10 1 ENGR 10 Introduction to Engineering (Part A)
Computer Science 1620 Loops.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 3 - Structured Program Development Outline.
Algorithm Design CS105. Problem Solving Algorithm: set of unambiguous instructions to solve a problem – Breaking down a problem into a set of sub- problems.
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
Computer Science 1620 Programming & Problem Solving.
Square Roots and Irrational Numbers
Chapter 3 Planning Your Solution
Elementary Algebra Exam 2 Material.
The switch Statement, DecimalFormat, and Introduction to Looping
ONE STEP EQUATIONS.
For a geometric sequence, , for every positive integer k.
Algebra Review Number Sense. These subgroups of numbers are often represented visually using a Venn Diagram.
Skills for October Rounds
Maths Notes Number 5. Decimals
Chapter 02 – Section 04 Rational Numbers.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Intermediate Algebra Prerequisite Topics Review Quick review of basic algebra skills that you should have developed before taking this class 18 problems.
Imaginary & Complex Numbers 5-3 English Casbarro Unit 5: Polynomials.
Goals of Course Introduction to the programming language C Learn how to program Learn ‘good’ programming practices.
Programing Concept Ken Youssefi/Ping HsuIntroduction to Engineering – E10 1 ENGR 10 Introduction to Engineering (Part A)
1 Problem Solving using computers Data.. Representation & storage Representation of Numeric data The Binary System.
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
Linear Equations and Inequalities. Much education today is monumentally ineffective. All too often we are giving young people cut flowers when we should.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Review for Exam2 Key Ideas 1. Key Ideas: Boolean Operators (2 > 3) || (3 < 29.3) A.True B.False C.Impossible to determine (22 > 3) && (3 > 29.3) A.True.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
 Here are a few review concepts before we start solving equations!
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
8-1 Compilers Compiler A program that translates a high-level language program into machine code High-level languages provide a richer set of instructions.
Section 5.3 The Rational Numbers Math in Our World.
Changing Bases. Base 10: example number ³ 10² 10¹ 10 ⁰ ₁₀ 10³∙2 + 10²∙1 + 10¹∙ ⁰ ∙0 = 2120 ₁₀ Implied base 10 Base 8: 4110 ₈ 8³ 8².
Chapter 7 Problem Solving with Loops
Algorithm Discovery and Design Objectives: Interpret pseudocode Write pseudocode, using the three types of operations: * sequential (steps in order written)
Controlling Program Flow with Decision Structures.
Algorithms and Pseudocode
Section 1.2. Why use it?  Some numbers are too big or too small to write using regular form (also called standard notation)  Using Scientific Notation.
Week 1 Real Numbers and Their Properties (Section 1.6, 1.7, 1.8)
26/06/ Iteration Loops For … To … Next. 226/06/2016 Learning Objectives Define a program loop. State when a loop will end. State when the For.
Algorithms and Flowcharts
Chapter 3 Fractions.
ALGORITHMS AND FLOWCHARTS
Loops BIS1523 – Lecture 10.
GC211Data Structure Lecture2 Sara Alhajjam.
CS1001 Programming Fundamentals 3(3-0) Lecture 2
Conditions and Ifs BIS1523 – Lecture 8.
Lesson 2 Programming constructs – Algorithms – Scratch – Variables Intro.
Algorithm Discovery and Design
3.1 Iteration Loops For … To … Next 18/01/2019.
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Chapter 3: Selection Structures: Making Decisions
Basic Concepts of Algorithm
Matlab Basics.
Presentation transcript:

CS 1000 H. James de St. Germain Problem Solving Writing a Program to Approximate Pi (or why is better than )

CS 1000 Problem We need pi… The computer needs pi… –At least for geometric, mathematical, physics, mechanical, civil, etc. computations The computer doesn’t know pi –Okay, it does know pi, but someone had to tell it. –What if you were that someone?

CS 1000 Option 1: Don’t use a Symbolic Name, just Memorize the digits…

CS 1000 The current unofficial (as of October ) world record is 100,000 decimal places, and was set by a Japanese mental health counselor named Akira Haraguchi, who is currently 59 years of age… Perhaps not the best use of Time?

CS 1000 Why Approximate Pi Pi is: –Irrational (X/Y ~= pi) –Infinite and Varied Computers cannot represent –Irrational numbers –Infinite numbers AH HA! You said in the previous slides that the computer knows pi! You were WRONG! The computer must only know an approximation of pi! –Perhaps we can do better than the Matlab Programmers?

CS 1000 Your “Assignment” (or word problems are fun) The magical number pi ( …) can be calculated by a sequence of subtractions and additions (e.g., 4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + 4/13 - 4/15 + etc). Write a program to calculate pi. First ask the user how many steps she wants to take. Make sure the inputted number is positive. Print out the final value.

CS 1000 Solving the Pi Problem Your Objective: –Turn Problem Statement into Code Process –Separate out and Identify (in high level English) the Steps necessary to accomplish the goal! –Convert each step into Pseudocode –Convert Pseudocode into Code

CS 1000 Things to Remember Computer programs execute ONE statement at a time and thus you have to think in a series of small steps while programming. While DESIGNING you should think in high level concepts, such as: –Get input –Calculate values (or use a loop to calc values) –Plot data Design First!

CS 1000 Programming Problem Calculate Pi Program This is DAUNTING! This is TOO Much! Must Not Panic. Must Not Panic! Lets break this into smaller easier steps!

CS 1000 Identify High Level Goals First re-read the problem statement: The magical number pi ( …) can be calculated by the following sequence of subtractions and additions.: 4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + 4/13 - 4/15 + etc Write a program to calculate pi. First ask the user how many steps she wants to take. Make sure the inputted number is positive. Print out the final value.

CS 1000 Break Down the Problem First lets break this down: –“Write a program to calculate pi. First ask the user how many steps she wants to take. Make sure the number is positive. Print out the value.” This becomes 1.The user must input how many steps in the calculation. –This “number of steps” must be positive. 2.The program calculates an approximation to pi. –We have a formula for this 3.Print out value of pi.

CS 1000 Program Decomposition Graph Calculate Pi Program Ask user for non negative number of steps Use formula to calculate pi Output the answer Much Better!

CS 1000 Or Flow Chart End Start Get Sequence Length Calculate Pi Print Output

CS 1000 Next: Analyze the Formula We are calculating the value of pi. Don’t panic, we are given the formula. – 4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + 4/13 - 4/15 + etc –Step

CS 1000 Oh my! It’s Math! Many people experience what I call the, “Oh my, its math!” phenomenon. Try not to let the idea that you are doing “Math” scare you into not thinking about the problem. The computer is going to do the work for you. Your job is to tell the computer how

CS 1000 So, first: Solve the Problem by Hand… … for a few simple examples: –If the user inputs the number zero, you ask again. –If the user inputs 1 you would print out that pie is 4 –If the user inputs 2 you would print out that pie is (4 – 4/3) –If the user inputs 3 you would print out that pie is (4 – 4/3 + 4/5) –etc, etc, etc Formula: 4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + 4/13 - 4/15 + etc Step: …

CS 1000 Looking for Patterns!

CS 1000 Write a For loop! for i = 1 : 1000 % for index = start:cnt:end –fprintf(‘%d ‘, i); end fprintf(‘\n’);

CS 1000 Write a While loop! value = 1 while ( value < 1000 ) % while ( true ) –fprintf(‘%d ‘, value); –value = value + 1; end fprintf(‘\n’);

CS 1000 Write a For Loop! for i=2:2:1000 –fprintf(‘%d ‘, i); end fprintf(‘\n’);

CS 1000 Write a While Loop! value = 2; while (value < 10000) –fprintf(‘%d ‘, value); –value = value + 2; end fprintf(‘\n’);

CS 1000 Write a Program. Use a While loop! current_digit = 1; while ( true ) –fprintf(‘%d ‘, current_digit); –if (current_digit == 1) current_digit = 0; –else current_digit = 1; –end end

CS 1000 Write a program. Use a For loop! for i = 1:10000 –if ( rem ( i, 2) == 0) fprintf(‘1 ‘); –else fprintf(‘0 ‘); –end end

CS 1000 Write a Loop Can you figure this one out?

CS 1000 Back to Pi: Looking for Patterns! The formula is: 4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + 4/13 – … What patterns do you see? –Write them down on your notes:

CS 1000 Does re-writing the formula help? Lets rewrite this on its side, step by step: 4 -4 / 3 +4 / 5 -4 / 7 +4 / 9 -4 / 11 …etc …

CS 1000 Making the pattern consistent. Lets make the pattern consistent: +4 / 1 -4 / 3 +4 / 5 -4 / 7 +4 / 9 -4 / 11 …etc …

CS 1000 Seek the Pattern What do we divide by? STEPDivision 14 / 1 24 / 3 34 / 5 44 / i4 / ? Symbolic of all possible values ? = some math with i Which is often written: ? = f(i) % some function of i

CS 1000 stepdivisor Write down a math equation to compute the “divisor” value from the “step” variable! divisor = 2 * step – 1 or ( ( 2 * i ) – 1) Seek the Pattern Compute the Divisor?

CS 1000 Seek the Pattern When do we Add? When do we Subtract? STEPAdd/Sub i ? Write your Pseudocode in your notes:

CS 1000 When do we Add? When do we Subtract? What is the pattern? If step number “i” is odd we add If step number “i” is even we subtract In Matlab: if ( odd(i) ) add the new value else subtract the new value end

CS 1000 Thus we have the following patterns: STEPAdd/Sub Value 1+4 / / / / iadd when i is odd4 / (2*i-1)

CS 1000 Time to Start Programming We know we are supposed to: 1.Query the user for how many iterations (how many steps, how big (i) gets) in our loop – If the number is not positive repeat step 1 2.Calculate the “current” approximation to pi using our formula 3.Output answer Calculate Pi Program Ask user for non negative number of steps Use formula to calculate pi Output the answer

CS 1000 Breaking the steps down We know we are supposed to: 1.Query the user for how many iterations (how many steps) in our loop number_of_steps = input(‘How many steps: ‘); 2.If the number is not positive repeat step 1 How do we repeat an unknown number of times? WHILE LOOP 3.Calculate the value of pi using our formula What are we doing? Repeating something a pre-defined number of times. What programming element do we use? FOR LOOP 4.Ouput the value

CS 1000 Getting the number of steps from the user We can combine our ideas into the following code: number_of_steps = input(‘How many steps: ‘); while (number_of_steps < 1) number_of_steps = input(‘How many steps: ‘); end –This is a DESIGN PATTERN that you will see many times in your programming career.

CS 1000 While Loop Design Pattern Ask for data While data is incorrect –Re-ask for data End while

CS 1000 Now for the calculation If we are calculating something, we had better have a variable for it: our_pi = 0; Note 1: Even though we are using the variable name our_pi, what we really mean is: “our approximation to the value of pi over the previous X steps” (but that would be too long a variable name) Note 2: we initialize the value of our variable to 0 to represent that no work has yet been done.

CS 1000 Now for the calculation our_pi = 0; % (our pi value starts at 0). Here is our formula ( at STEP=i, compute 4 / ( i*2 -1 ), and add to our_pi ) –our_pi = our_pi + ( 4 / ( (i * 2) – 1 ) ; remember: sign alternates but initially lets just use ‘+’ Thus we need a Loop for i = 1 to number_of_steps do calculation end

CS 1000 Calculation continued: Lets combine our steps: –Remember Initialize variable Write loop Insert formula into loop our_pi = 0; % (our pi value starts at 0). for i = 1 : number_of_steps our_pi = our_pi + ( 4 / ( (i * 2) – 1 ) ); end % read this to be, “Our approximation of Pi becomes equal to the old approximation of Pi plus (or minus) the new computation.”

CS 1000 Sign Alternates! We need to take into account the fact that the sign alternates. There are many options: 1.Mathish expression –add if odd ( i ) 2.Another Math expression –sign = ( -1 ^ (i+1) ); 3.A boolean flag (called a toggle): sign_is_positive = true; % then change to false. sign_is_positive = ~sign_is_positive; % inside loop 4.Others are possible

CS 1000 Alternating Sign using odd even if ( odd(i) ) our_pi = our_pi + % PLUS formula else % i must be even our_pi = our_pi - % MINUS formula end

CS 1000 Alternating Sign using a Boolean if (time_for_a_negative) our_pi = our_pi - % MINUS formula time_for_a_negative = ~time_for_a_negative; else % only alternative is time for a positive our_pi = our_pi + % PLUS formula time_for_a_negative = ~time_for_a_negative; end

CS 1000 Cleaning up Duplicate Code if (time_for_a_negative) our_pi = out_pi - % MINUS formula else % only alternative is time for a positive our_pi = our_pi + % PLUS formula end time_for_a_negative = ~time_for_a_negative;

CS 1000 Alternating Sign using Math our_pi = … our_pi + (formula * -1^(i+1)); Advantage: No IF statement Disadvantage: Perhaps Compute Intensive

CS 1000 Insert alternating sign code Old code: our_pi = 0; % (our pi value starts at 0). for i = 1 : number_of_steps our_pi = our_pi ? ( 4 / ( (i * 2) – 1 ) ); end New code using “boolean flag” to alternate add/sub our_pi = 0; % (our pi value starts at 0). sign_is_positive = true; for i = 1 : number_of_steps if (sign_is_positive == true) our_pi = our_pi + ( 4 / ( (i * 2) – 1 ) ); else our_pi = our_pi - ( 4 / ( (i * 2) – 1 ) ); end sign_is_positive = ~sign_is_positive; % must switch each time end

CS 1000 Finally: Print out the Answer This step is easy! (I hope!) fprintf(‘the value of pi over %d iterations is approximated as %f\n’, number_of_steps, our_pi); %d – print integer number (whole number) %f – print float number (with decimal point) \n – print a newline

CS 1000 Summary What we did: –Analyzed program from the TOP  DOWN. –Found major components of program. –For each major component, wrote pseudocode –For each section of pseudocode we wrote actual code

CS 1000 What does the final program look like? % % Program by : H. James de St. Germain % This program calculates the value of pi, using the formula % pi = 4 – 4/3 + 4/5 – 4/7 + 4/ number_of_steps = input('How many steps: '); while (number_of_steps < 1) number_of_steps = input('How many steps: '); end our_pi = 0; sign_is_positive = true; for i = 1 : number_of_steps if ( sign_is_positive == true ) our_pi = our_pi + ( 4 / ( ( i * 2 ) - 1 ) ); else our_pi = our_pi - ( 4 / ( ( i * 2 ) - 1 ) ); end sign_is_positive = ~sign_is_positive; end fprintf('the value of pi over %d iterations is %f\n', number_of_steps, our_pi);

CS 1000 Lets Convert to C

CS 1000 Questions?