Upload
shannon-fields
View
228
Download
0
Tags:
Embed Size (px)
Citation preview
LSP 121LSP 121
Computers and Computers and
Algorithmic ProcessesAlgorithmic Processes
What Is A Processor?What Is A Processor?
All computers, cell phones, iPods, iPads, All computers, cell phones, iPods, iPads, Kindles, automobiles, … have a processor Kindles, automobiles, … have a processor (or two or more) inside(or two or more) inside
A processor accepts some kind of input, A processor accepts some kind of input, performs a computation, and produces performs a computation, and produces some kind of outputsome kind of output
For example, one processor in an For example, one processor in an automobile inputs engine conditions and automobile inputs engine conditions and outputs fuel control outputs fuel control
Multi-taskingMulti-tasking
Many processors can work on only ONE Many processors can work on only ONE task at a time! task at a time! (Dual-core/quad-core (Dual-core/quad-core processors are exceptions to this rule)processors are exceptions to this rule)
But they jump from one task to the next so But they jump from one task to the next so quickly, it appears they are working on quickly, it appears they are working on many tasks simultaneouslymany tasks simultaneously
We say these processors can multi-taskWe say these processors can multi-task Can you multi-task?Can you multi-task?
Multi-taskingMulti-tasking
Not too wellNot too well Many people can do two tasks at once, as Many people can do two tasks at once, as
long as one of the tasks doesn’t require long as one of the tasks doesn’t require much cognitive thought (such as casual much cognitive thought (such as casual listening to music)listening to music)
But three or more tasks? Or tasks that But three or more tasks? Or tasks that require concentration? Sorry, you aren’t a require concentration? Sorry, you aren’t a computer. computer.
Sometimes We ActSometimes We ActLike ProcessorsLike Processors
Let’s say you work alone in a candy storeLet’s say you work alone in a candy store You (the processor) wait on customers, ring You (the processor) wait on customers, ring
up their orders, and answer the phoneup their orders, and answer the phone On slow days, you sit staring out the On slow days, you sit staring out the
window, waiting for input (someone to enter window, waiting for input (someone to enter the shop or for the phone to ring)the shop or for the phone to ring)
(What happens on Valentine’s Day? You (What happens on Valentine’s Day? You work REALLY fast or you hire another work REALLY fast or you hire another processor or the line goes out the door!)processor or the line goes out the door!)
A Sample ComputerA Sample Computer
Let’s examine your cell phoneLet’s examine your cell phone What are the inputs?What are the inputs?
Buttons, touch screen, cell tower calling you, Buttons, touch screen, cell tower calling you, microphone, keypadmicrophone, keypad
What are the outputs?What are the outputs? Speaker, screen, sending signal to cell towerSpeaker, screen, sending signal to cell tower
A Sample ComputerA Sample Computer
The cell phone processor waits* until an The cell phone processor waits* until an input comes ininput comes in
When an input comes in, the processor When an input comes in, the processor processes something, then maybe processes something, then maybe produces an output (or maybe it just waits produces an output (or maybe it just waits for more input)for more input)
* Some spin in a loop and some “go to sleep”* Some spin in a loop and some “go to sleep”
One Possible ScenarioOne Possible Scenario
There are a number of “functions” running There are a number of “functions” running in a cellphonein a cellphone One function converts data into a signalOne function converts data into a signal Another converts a signal into dataAnother converts a signal into data Another accepts keystrokes on the keypadAnother accepts keystrokes on the keypad Another accepts touches on the touch screenAnother accepts touches on the touch screen
(We’ve seen other functions: PMT, NORMDIST, LOG)(We’ve seen other functions: PMT, NORMDIST, LOG)
REPEAT THE FOLLOWING STEPS
Is there data from the keypad? If yes, then process it.
Is there data from the touch screen? If yes, then process it.
Is there a signal coming in from a cell tower? If yes, …
Is there data that has to go out to a cell tower? If yes, …
Is there data that has to go out to the speaker? If yes, …
Is there data coming in from the microphone? If yes, …
UNTIL SHUT-OFF SEQUENCE IS CALLED
These steps form what we call an algorithmic process.
What Is An Algorithmic Process?What Is An Algorithmic Process?
An ordered series of steps that when An ordered series of steps that when applied to a problem produces a solutionapplied to a problem produces a solution
Some call it “thinking logically”Some call it “thinking logically” Others refer to it simply as Others refer to it simply as problem solvingproblem solving Often simply called an Often simply called an algorithmalgorithm
Why Should We Know What An Why Should We Know What An Algorithmic Process Is?Algorithmic Process Is?
Many things in life are algorithmic processes:Many things in life are algorithmic processes:
Music, dance (such as ballet), art, biology (natural Music, dance (such as ballet), art, biology (natural selection, nature), math, economics, life (buying a car or selection, nature), math, economics, life (buying a car or house, career changes, grad school choice), workhouse, career changes, grad school choice), work
You can create useful You can create useful macrosmacros in Access, Excel, in Access, Excel, and Wordand Word
You can create iPhone apps and maybe make You can create iPhone apps and maybe make lots of moneylots of money
Why Should We Know What An Why Should We Know What An Algorithmic Process Is?Algorithmic Process Is?
You can write simple programs to analyze data You can write simple programs to analyze data and write the next article exposing cheaters in your and write the next article exposing cheaters in your school district (like Freakonomics)school district (like Freakonomics)
At work you can create financial models At work you can create financial models (business), reprogram digital synthesizers/ (business), reprogram digital synthesizers/ converters (music, cinema), design political converters (music, cinema), design political districts (poly sci), weather prediction (earth districts (poly sci), weather prediction (earth sciences), create neural networks (psychology), sciences), create neural networks (psychology), model cultural evolution (sociology), diabetes model cultural evolution (sociology), diabetes management (medicine), create genetic algorithms management (medicine), create genetic algorithms (biology)(biology)
Computers and AlgorithmsComputers and Algorithms
Computers are very good at executing Computers are very good at executing algorithmsalgorithms
But computers require precise instructions But computers require precise instructions to perform an operationto perform an operation
The instructions cannot be ambiguous The instructions cannot be ambiguous (must be clear and concise)(must be clear and concise)
Let’s see what this means: Let’s do Let’s see what this means: Let’s do Activity 12Activity 12
What is an Algorithm?What is an Algorithm?
Algorithms consist of four basic types of Algorithms consist of four basic types of operations or instructions:operations or instructions:1. Sequential operations, e.g. Add 1 cup of 1. Sequential operations, e.g. Add 1 cup of
butter; Subtract the amount of the check butter; Subtract the amount of the check from the current account balance; Set the from the current account balance; Set the value of x to 1value of x to 1
2. Conditional operations, e.g. If the mixture is 2. Conditional operations, e.g. If the mixture is too dry, then add ½ cup water; If the current too dry, then add ½ cup water; If the current account balance < 0, then transfer funds account balance < 0, then transfer funds immediatelyimmediately
What is an Algorithm?What is an Algorithm?
3. Iterative operations, e.g. Repeat the previous 3. Iterative operations, e.g. Repeat the previous two steps until the mixture has thickened; two steps until the mixture has thickened; Repeat the following five steps until there Repeat the following five steps until there are no more checks to be processed; are no more checks to be processed; Repeat steps 1,2 and 3 until the value of y is Repeat steps 1,2 and 3 until the value of y is equal to +1equal to +1
4. Calling a pre-existing algorithm (or function), 4. Calling a pre-existing algorithm (or function), e.g. Make a e.g. Make a reductionreduction with your sauce; with your sauce; date := getDate(); =normdist(x, mean, date := getDate(); =normdist(x, mean, stdev, true)stdev, true)
ExampleExample
Add two values:Add two values: 3254232542
+ 42892+ 42892
How would you describe this operation to someone in grade school?
Average Miles Per GallonAverage Miles Per Gallon
Step 1: Get values for Step 1: Get values for gallons usedgallons used, , starting mileagestarting mileage, , ending mileageending mileage
Step 2: Set the value of Step 2: Set the value of distance driven distance driven to to ending mileage ending mileage – – starting mileagestarting mileage
Step 3: Set the value of Step 3: Set the value of average miles per average miles per gallongallon to to distance driven /distance driven / gallons usedgallons used
Step 4: Print the value of Step 4: Print the value of average miles average miles per gallonper gallon
Step 5: StopStep 5: Stop
Modified Average Miles Per Modified Average Miles Per GallonGallon
Step 1: Get values for Step 1: Get values for gallons usedgallons used, , starting mileagestarting mileage, , ending mileageending mileage
Step 2: Set the value of Step 2: Set the value of distance driven distance driven to to ending mileage ending mileage – – starting mileagestarting mileage
Step 3: Set the value of Step 3: Set the value of average miles average miles per gallonper gallon to to distance driven distance driven / / gallons gallons usedused
Step 4: Print the value of Step 4: Print the value of average miles average miles per gallonper gallon (continued on next slide) (continued on next slide)
Modified Average Miles Per Modified Average Miles Per Gallon ContinuedGallon Continued
Step 5: If Step 5: If average miles per gallon average miles per gallon is is greater than 25.0 thengreater than 25.0 then Print the message “You are getting good gas Print the message “You are getting good gas
mileage!”mileage!”
ElseElse Print the message “You are NOT getting good Print the message “You are NOT getting good
gas mileage. Buy a Chevy Volt”gas mileage. Buy a Chevy Volt” Step 6: StopStep 6: Stop
Inviting Friends to a PartyInviting Friends to a Party Step 1: Step 1: For each of your friends do this loop:For each of your friends do this loop:
Step 2: If this a close friend thenStep 2: If this a close friend then• Put them in the e-vite listPut them in the e-vite list
ElseElse• Put their name on the “B list”Put their name on the “B list”
Step 3: Check off their nameStep 3: Check off their name Repeat Steps 2 and 3 until no more friendsRepeat Steps 2 and 3 until no more friends
Step 4: Count number of guests (for food)Step 4: Count number of guests (for food) Step 5: Mail invitationsStep 5: Mail invitations Step 6: StopStep 6: Stop
Next Quarter’s Class ScheduleNext Quarter’s Class Schedule I need a history class, an arts & literature I need a history class, an arts & literature
class, and a religious dimensions classclass, and a religious dimensions class I need to take the next two classes in my I need to take the next two classes in my
majormajor I don’t want a class before 10:00amI don’t want a class before 10:00am I definitely don’t want a Saturday classI definitely don’t want a Saturday class If I can get all my classes on Mon/Wed …If I can get all my classes on Mon/Wed …
This is NOT a trivial algorithm, yet you do this This is NOT a trivial algorithm, yet you do this each quarter!each quarter!
Let’s Try Another ExampleLet’s Try Another Example
Let’s try one together. Let’s try one together. Write the pseudocode Write the pseudocode to examine student scores on an exam. You to examine student scores on an exam. You want to count how many students passed (>=70) want to count how many students passed (>=70) and how many students failed (<70). When you and how many students failed (<70). When you hit the end of the list, print the total number of hit the end of the list, print the total number of students that passed and the total number of students that passed and the total number of students that failed.students that failed.
Classic Applications of Classic Applications of AlgorithmsAlgorithms
Sorting large data setsSorting large data sets Searching for data (like Google)Searching for data (like Google) Routing a packet across the InternetRouting a packet across the Internet Finding an optimal solution to a problem (such Finding an optimal solution to a problem (such
as finding the best route on a map using a GPS as finding the best route on a map using a GPS device or mapping web site)device or mapping web site)
Detecting and correcting transmission errorsDetecting and correcting transmission errors Compressing dataCompressing data Making data secureMaking data secure
AliceAlice
For our next activity, let’s use the programming For our next activity, let’s use the programming system called Alicesystem called Alice
Look for the application Alice on your machine. Look for the application Alice on your machine. (You can download Alice at home for free from (You can download Alice at home for free from alice.org)alice.org)
Run the Skater Tutorial first, to get an idea of Run the Skater Tutorial first, to get an idea of how Alice workshow Alice works
Observe the if statements and loop statements Observe the if statements and loop statements as you insert them into your “code”as you insert them into your “code”
Do Activity 13 - AliceDo Activity 13 - Alice
Visual BasicVisual Basic
Here is an example of an If statement:
if Row < 100 then
Cells(Row, 2) = 1
else
Cells(Row, 2) = 0
end If
Visual BasicVisual Basic
Here is an example of a while loop:
Counter = 0
while Counter < 20
Counter = Counter + 1
end while
Visual BasicVisual Basic
Here is an example of a For loop
for Row = 1 To 50
Y = rnd(a)
X = X + Y
next Row
You can now try Activity 14
2828
Compression–Lossless versus Compression–Lossless versus LossyLossy
Compression is a technique used to Compression is a technique used to squeeze data into a smaller spacesqueeze data into a smaller space
Two basic groups of compression:Two basic groups of compression: Lossless – when data is uncompressed, Lossless – when data is uncompressed,
original data returnsoriginal data returns Lossy – when data is uncompressed, you do Lossy – when data is uncompressed, you do
not have the original datanot have the original data
2929
Where is Compression Used?Where is Compression Used?
DVDs and Blu-Ray moviesDVDs and Blu-Ray movies Broadcast television and cable television Broadcast television and cable television
signalssignals Music players such as iPods and Nanos, Music players such as iPods and Nanos,
as well as the music players within cell as well as the music players within cell phonesphones
Transferring large data files over the Transferring large data files over the InternetInternet
3030
Lossless or Lossy?Lossless or Lossy?
Compress a financial file? Compress a financial file? You want lossless (e.g. Lempel-Ziv)You want lossless (e.g. Lempel-Ziv)
Compress a video image, movie, or audio Compress a video image, movie, or audio file?file? Lossy is usually OK (e.g. MPEG, JPEG, MP3)Lossy is usually OK (e.g. MPEG, JPEG, MP3)
Some people like their music Some people like their music uncompressed (e.g. FLAC, ALAC, uncompressed (e.g. FLAC, ALAC, Monkey’s Audio)Monkey’s Audio)
3131
Lossless CompressionLossless Compression
Run-length encodingRun-length encoding Replaces runs of 0s with a count of how many Replaces runs of 0s with a count of how many
0s.0s.00000000000000100000000011000000000000000000001…1100000000000100000000000000100000000011000000000000000000001…11000000000001
^̂
(30 (30 0s)0s)
14 9 0 20 30 0 1114 9 0 20 30 0 11
3232
Run-length Encoding Run-length Encoding (continued)(continued)
Now replace each decimal value with a 4-Now replace each decimal value with a 4-bit binary value (nibble)bit binary value (nibble) Note: If you need to code a value larger than Note: If you need to code a value larger than
15, you need to use two consecutive 4-bit 15, you need to use two consecutive 4-bit nibblesnibbles
The first is decimal 15, or binary 1111, and the The first is decimal 15, or binary 1111, and the second nibble is the remaindersecond nibble is the remainder
For example, if the decimal value is 20, you For example, if the decimal value is 20, you would code 1111 0101 which is equivalent to would code 1111 0101 which is equivalent to 15 + 515 + 5
3333
Run-length Encoding Run-length Encoding (continued)(continued)
If you want to code the value 15, you still If you want to code the value 15, you still need two nibbles: 1111 0000need two nibbles: 1111 0000
The rule is that if you ever have a nibble of The rule is that if you ever have a nibble of 1111, you must follow it with another nibble1111, you must follow it with another nibble
3434
Lossy CompressionLossy Compression
Audio and video don’t compress well using Audio and video don’t compress well using run-length compressionrun-length compression
And it is possible to trick the eyes and earsAnd it is possible to trick the eyes and ears So use lossy compression on video and So use lossy compression on video and
musicmusic
3535
Video CompressionVideo Compression
In one color video frame, not much is alikeIn one color video frame, not much is alike But what about from frame to frame?But what about from frame to frame?
Send a frame, store it in a bufferSend a frame, store it in a buffer Next frame is just difference from previous Next frame is just difference from previous
frameframe Then store that frame in buffer, etc.Then store that frame in buffer, etc.
3636
5 7 6 2 8 6 6 3 5 66 5 7 5 5 6 3 2 4 78 4 6 8 5 6 4 8 8 55 1 2 9 8 6 5 5 6 6First Frame
5 7 6 2 8 6 6 3 5 66 5 7 6 5 6 3 2 3 78 4 6 8 5 6 4 8 8 55 1 3 9 8 6 5 5 7 6Second Frame
0 0 0 0 0 0 0 0 0 00 0 0 1 0 0 0 0 -1 00 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0Difference
Lossy Compression (continued)Lossy Compression (continued)
3737
Lossy Compression (continued)Lossy Compression (continued)
What about a single image?What about a single image? JPEG (Joint Photographic Experts Group)JPEG (Joint Photographic Experts Group) Consists of 3 phases:Consists of 3 phases:
Discrete cosine transformations (DCT)Discrete cosine transformations (DCT) QuantizationQuantization Run-length encodingRun-length encoding
Data Encryption/SecurityData Encryption/Security
Go ahead and do Activity 15Go ahead and do Activity 15
Data ErrorsData Errors
Go ahead and do Activity 16Go ahead and do Activity 16