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?