Extensions

Extension 1: Speed Limit Fine Calculator (3 points):

You will calculate the fine one would have to pay for going over the speed limit in the state of Massachusetts
according to the
Massachusetts DMV.

By completing this work, you demonstrate that you can:

Create a Java class on your own

Arrange for the class to take inputs of interest

Compute output values of interest

Produce meaningful output based on your computations

Have you ever received a ticket for speeding?
If so, how do you feel about it? Were you going more or less than 10 miles over the speed limit?
The objective of this extension is not only to allow you to practice assignment statements and data types but also for you to create a
practical tool, though of course we hope you never need to compute a speeding
fine for yourself.

Consider the following story:

Pat is driving a Mini Cooper at 85 MPH on a
road that has the speed limit of 60 MPH.

Pat is therefore going 25 MPH over the speed limit.

If Pat is caught speeding, what would be Pat's fine?

For this assignment, we model the fine after Massachusetts law:

A fine is assessed only if the driver's speed is at least 10 MPH over
the speed limit.

For the first 10 MPH over the speed limit, the fine is $50 no matter what

End of extension 1

Extension 2: Image Processor (6 points):

Background

Pixels

The word pixel stands for Picture Element. A pixel is a small part
of a picture. Pixels are the little dots that make up LCD
screens. When you see a low-resolution picture that is grainy, the
grain you're seeing are the pixels.

Representing color in Java

Pixels are made up of 3 colors: red, green, and blue (hence the
term RGB). The color of a pixel is made up of a combination of the
intensities of each of red, green, and blue components. Intensities range from 0 (meaning none of that color is present) to 255
(meaning as much as possible of that color is present). You
declare a new pixel by coding

new Color(redValue, greenValue,blueValue)

where redValue is the intensity (an integer between 0 and 255) of
red, greenValue is the intensity of green, and blueValue is the intensity of blue.

For example, you get the color black with new Color (0,0,0) (0
intensity for all colors). You get red with new Color (255,0,0)
(highest intesity for red, 0 intensity for green and blue).

Filters

This work involves writing a number of filters that are applied to
images to achieve a given result. There are two kinds of methods that
you complete, and each is described below:

int foo(int pixelComponent)

Methods with the above signature take in a single pixel component
intensity value: an integer between 0 and 255 inclusively.
They are obligated to return an intensity value as their result.

These methods are used by the course software as shown below:

A Color object is broken into its red, green, and blue
components.

Each component is passed to your foo method, and the
result of that function is retained.

The three results are combined into a new Color object.

In other words, the foo function is used as a filter on each
of a Color's components. The foo function is unaware
of which component it is processing: it treats each equally.

Color bar(Color c)

Methods with the above signature accept and produce a standard Java
Color object. These methods can themselves decompose a Color
object into its components and create a resulting Color object
to achieve whatever effect is desired.

Project: Image Processing Methods

In Eclipse, open the extensions source folder and
then open the imageprocessor package. Find and open the
ImageProcessor class.

This is the main program you run to see the results of your work.

Go ahead and run it as a Java application.
You should see a window pop up with
some images preloaded.

Try the darker filter. It has been implemented for you, and
it should produce an image in the Target window that resembles
the image in the source1 window, but is a bit darker.

Try the combine filter. It has also been implemented but
its effects may seem a bit strange. You will soon implement a smarter version
of this kind of a filter.

The other methods are not yet implemented, but you are free to try
them.

By the way, you can drag images between the icon panel at the top and the working
panels in the middle, or vice versa, so that you can manipulate
other images than the ones that are preloaded.

You can also load your own images by clicking on the icon that resembles
a plus sign.

Directions:

First, right click on the ImageProcessorTest class, and Run As a JUnit Test.

On the left you should see a whole bunch of
test names with red or blue x's by them, indicating that they are not being passed.

Every time you complete a piece of code correctly, one of the tests will pass,
and a small green x will appear beside it.

Once all of the tests pass, a satisfying green bar will appear in place of the red one that you see now. You will
not get this green bar in this extension, though, because you will not be doing any work on the bgSubtract or bdReplace methods.
To get the green bar you must go on to the next extension.

Now open the Filters class and begin your work as described
below.

It is strongly suggested that you re-run the unit test, and run ImageProcessor to test each filter after its
completion before you move on to the next filter. This will ensure that you are making progress and not going down a wrong path.

Complete the provided stub
methods as described below.
In the method bodies, use mathematical expressions. Do not use
a conditional (if) statement.

Intensity filters

Use no conditional execution for this part: only arithmetic expressions
as you have learned them in Module 1.

Complete the method called copy, so that each
provided intensity value is copied exactly
from the source to the target panel.

Hint: This is a very
simple method.

Complete the method that will composite the images
in the
two source panels by averaging their components. This method accepts two
parameters, which are color components from the two source panels.

Complete the method called negative that will
produce the
negative image by inverting the intensity of each component.

For
example, if the parameter value is 0, you should return 255. If the
parameter value is 1, you should return 254, and so on.

Complete the method posterize that will reduce the
number of possible colors in an image. For a given color component, your
method will choose between
two intensities, 0 or 255, which correspond to that color component
being turned off or on completely.
So, since each color has three
components (red, green, and blue), you will end up with an image that
has only 8 different colors.

Remember that you are not
allowed to use conditionals (if) statements for this part of the lab.

Hint: : Recall that color components
are in the range 0-255. Also, recall that if you divide an int by
another int, the result number will be truncated. For example,
130 / 128 = 1, but
125 / 128 = 0.

Create and test methods (whose parameters and return values are Colors)
with the following specifications.

Complete the method brighter that will return, for
each pixel, a Color that is brighter than
the original.

The
Color
class makes this easy because it already
provides a
brighter()
method that returns a brighter color.

If c is a color, then c.brighter() is a brighter version of c's color.

Complete the method grayscale that will make a
grayscale image from a color image.
To do this, you will take in one Color parameter (the Color object for
a pixel from the original image) and
will produce a new Color in which all the components (red, green, and
blue) have the same value.

Hint: To choose which value, average the three components of the
original color.

More Color filters

OK, now you can use if statements!

Complete the method blackAndWhite that produces a
black and white image by returning, for each pixel, a Color that is
either black or white, depending upon the overall intensity of the
original color.

For your return value, use the constant Color.BLACK
or Color.WHITE. It's up to you how to decide when a
color's components, taken as a whole, should be considered black or
white.

Complete the method combineBrighter that combines
two images by choosing for each pixel the color from the image that has
the brighter pixel in that location. To determine which pixel is
brighter, compare the sums of the red, green, and blue components of
the two pixels. Since the ProcessorTool will run your method for every
pair of pixels, the resulting image will have some pixels from the
first image and some from the second image.

Demo

You must pass all of the unit tests, except for the ones for bgSubtract and bgReplace

Your TA should be able to play with your
ImageProcessor and deem it sufficient

When you done with this extension, you must be cleared by the TA to receive credit.

Commit all your work to your repository

Fill in the form below with the relevant information

Have a TA check your work

The TA should check your work and then fill in his or her name

Click OK while the TA watches

If you request propagation, it does not happen immediately,
but should be posted in the next day or so

End of extension 2

Extension 3: Image Processor Continued (4 points):

This is a continuation of the previous extension. It is therefore
suggested that you
do the previous extension first.

Directions:

The main program you should run for this extension is Background, which
conveniently
sets up the images in the bar and panels for you to do this work.

So run Background as a Java application. You will see two
similar images in the source panels, and some other images in the image
bar.

Open the Filters class and begin your work as described
below.

Two more Color filters

You can use if statements for this work.

Complete the method bgSubtract so that it returns
a Color as follows:

If the source1Color and source2Color colors are
sufficiently similar, return Color.BLUE. The idea is to subtract
the background so that what is common between the two source images is shown
in blue.

We will define a new term for this lab, the Saturation Tolerance. What this tells us is how different two colors can be, and still be considered
sufficiently similar. For instance; if the Saturation Tolerance is 10, one color has a red value of 130, and another color has a
red value of 138, these would be considered sufficiently similar. But if one color had a red value of 35 and another had a red value of 50, they would not
be considered sufficiently similar

Otherwise, return source1Color.

An example is shown below:

Where the two images are similar, the corresponding pixel in the
target image is blue, because your method returned Color.BLUE.
Where the images differ, the first image is shown in the target,
because your method returned the pixel color from the first image.

Complete the method bgReplace that functions as
follows:

If the source1Color is Color.BLUE, then return
the source2Color.

Otherwise, return source1Color.

The effect of this filter is to replace the blue color from the first image
with the corresponding pixels from the second image.

To see this work, perform the following steps:

Drag the blue-screen image from the target panel and drop it into the leftmost source panel. The GUI should replace what was there with the blue-screen
image.

Drag the other two-bear picture (the reverse of the one shown in the
source panel) from the top icon bar into the middle source panel.

After dragging these images around the GUI, the results should resemble the
following:

Note: No transformation is applied yet. The copy operation appears
as the menu choice but the Go button was not pressed.

Now apply the bgReplace filter, and the results resemble the
following:

For fun, drag the chicken image from the top icon bar into the middle source panel, and reapply the bgReplace filter. The results should
resemble the following:

The chicken is a smaller image, so it did not take up the entire size of
the bear image.

To Demo

You must have received the satisfying green bar telling you that you've passed all of the ImageProcessor tests. Your TA must also be able to play with your
ImageProcessor and be satisfied.

When you done with this extension, you must be cleared by the TA to receive credit.

Commit all your work to your repository

Fill in the form below with the relevant information

Have a TA check your work

The TA should check your work and then fill in his or her name

Click OK while the TA watches

If you request propagation, it does not happen immediately,
but should be posted in the next day or so

This demo box is for extension 1.3

Last name

WUSTL Key

Propagate?

(or your numeric ID)

Do not propagate

e.g.

Smith

j.smith

1

Copy from 1 to all others

2

Copy from 2 to all others

TA:
Password:

End of extension 3

Extension 4: Expected Value (3 points):

Authors

Alan Waldman

Background

How do you feel about money, risk, and job satisfaction?
In this extension you will
examine some simple yet powerful ideas from economics, and you will
write code to compute how a person should behave based how he or she
views risk, reward, and job satisfaction.

The concepts we explore are as follows:

Utility

Utility
is an economic term referring to the total satisfaction you
derive or receive from some action or activity.

Given the choice of two activities and absent any other
concerns, a rational person would chose the activity
that yielded the higher utility.

Expected Value

If there is uncertainty about outcomes, then the expected
value of a given outcome is the product of its probability of occurring and
the value of achieving that outcome.

Let's consider the following two examples:

You are given $1. The probability of this event is 1, and your
value for achieving the outcome is $1, so your expected value is $1.

You enter into a (no-cost) lottery with 9,999 other people for a chance to win
$10,000. If the probability of the winner is uniformly distributed among those
who enter the lottery, you win $10,000 with probabilty 0.0001 and you lose (win $0)
with probability 0.9999. The expected value computation for this
scenario is as follows:

(.0001 × $10,000) &plus; (.9999 × $0)

Your expected value here is therefore also $1.

Based only on expected value, a person confronted with a choice on the
above two scenarios would have no reason to pick one over the other, since
the expected value is the same.

Now suppose the money given to you for certain
in the first scenario is doubled to $2. A rational person would surely
pick $2 over the lottery entry, because $2 is twice the expected value of
the lottery outcome.

However, we know there are people who would choose entering the lottery over
receiving a sure $1 or $2.

In the Powerball Lottery,
your chances of winning are
1 in 175,223,510. So a rational person shouldn't buy a ticket if the jackpot
is under $175M.
But allegedly rational people do buy tickets for jackpots under that
threshold.

How can we account for this behavior?
Read on.

Expected Utility Theory

The above analysis assumes a linear value for wealth.
We can account
for those who favor or avoid risk using
Expected Utility Theory.
This theory admits that rational people may have nonlinear views of
wealth. This means that you may like $1,000 more (or less) than 1,000 times as much
as you like $1.
Let's look at three examples:

Expected utility function

Notes

u(d) = d

Linear value of wealth. The above analysis applies to such
a person. NOTE TO SELF: 2nd derivative 0 here

u(d) = d2

This person values $10,000 the same way a linear
person would value $100,000,000.

In
the scenario given above, this explains why a person would enter the
lottery. The person's perceived value of winning $10,000 is
NOTE TO SELF: show the application of u here
$10,0002=$100,000,000, which at probability 0.0001 yields an expected
utility of $10,000: far greater than the $1 given for certain.

An alternate view is that this person has a linear view of wealth
(u(d)=d)
but an
unrealistic view of the probability of winning. For example, if this
person holds the false belief that the probability of winning is 0.1 instead
of .0001, then
the expected value jumps
from $1 to $1,000 using a linear function for expected utility.
Because economists try to model human behavior assuming rationality, they
translate this inflated view of luck into a nonlinear view of wealth.

Thus, the function u(d)=d2 captures a form of
risk-loving behavior.
More generally, when viewed from below, any convex function,
of which u(d)=d2 is an example, models risk-loving behavior.
NOTE TO SELF: 2nd derivative is positive

Such a person is either more certain of winning than
probabilities would indicate, or alternatively has a convex expected
utility function.

u(d) = sqrt(d)

On the other hand, this concave function captures risk-averse
behavior. In the lottery scenario, a win of $10,000 would feel like a win
of only $100 to this person. With a .0001 probability of winning, the
expected utility under this function is only 1 cent. Such a person would
not enter the lottery even if the no-risk payoff were reduced from $1 to 2 cents.
NOTE TO SELF: 2nd derivateive is negative here

Problem

Suppose you are trying to decide between one of the following
two careers:

Gamer

You join a start-up company, which is exciting and
could have high pay-off, but this venture might
fail.
Let's say
you succeed with probability p, and if so you will
earn $190,000. But if you fail (with probability 1-p), you earn only $5000.

Programmer

This job has no risk, and offers a salary in the range
of $110,000 to $160,000. Your salary will be determined by a random
choice of a value drawn uniformly from that range.

Procedure

Do this work by createing a class in the expectedvalue
package of the extensions folder.

Let's begin by assuming you have linear value for money. Based on
the above description, write a program that does the following:

Prompts the user for a value for p, which is the probability of
the game start-up venture succeeding. The text of your prompt should
be a meaningful message.

Think about the type of p. Also what is a good variable name
for this concept?

Given p, compute the expected value of the gamer-job outcome.

Use the equation for the Expected Value that is shown in the background section. Again, think about the type you need to represent the computed value,
and think of a good name for this concept.

Now pick a salary for the programming job by choosing a random value
between $110,000 and $160,000.

Print both outcomes and a message that indicates whether you should
accept the gamer job over the programmer job depending on which one will give you the most money, according to your calculation.
Such output might resemble:

Gamer: $97,500
Programmer: $115,000
You should be a gamer and not a programmer? false

Run your program for multiple values of p to be sure that your output
makes sense.

Now lets assume that you DON'T have a linear value of wealth. Lets assume that your utility for wealth given your job differs as follows:

EU (Gamer): 3*sqrt(wealth)

EU (Programmer): 2*sqrt(wealth)

Now:

Take the values for the wealth for the two jobs that you got before, and plug them into the above utility functions

Print both outcomes and a message that indicates whether you should
accept the gamer job over the programmer job depending on which one will give you the most utility, according to your calculation.

When you done with this extension, you must be cleared by the TA to receive credit.

Commit all your work to your repository

Fill in the form below with the relevant information

Have a TA check your work

The TA should check your work and then fill in his or her name

Click OK while the TA watches

If you request propagation, it does not happen immediately,
but should be posted in the next day or so

This demo box is for extension 1.4

Last name

WUSTL Key

Propagate?

(or your numeric ID)

Do not propagate

e.g.

Smith

j.smith

1

Copy from 1 to all others

2

Copy from 2 to all others

TA:
Password:

End of extension 4

Extension 10: Course Grade Calculator (3 points):

Authors

Brennan Morell

Jarett Gross

Issues:
This will become part of studio for this module.
They'll do some warm up stuff and then this, which will force them
to understand the grading rubric.

Background

For this assignment, you will develop a calculator that will determine your final score for the course
based on the grades you received.

Procedure

Have your program accept the following inputs and store these input values into variables:

The name of the person whose grade is being calculated.

The number of participation points received.

The number of quiz points received.

The number of studio points received.

The number of lab points received.

The number of extension points received.

The number of exam one points received.

The number of exam two points received.

The number of lab 10 + quiz 10 points received.

Use ArgsProcessor to accept input and store these values using variables with the appropriate data types.

Calculate the (unrounded) course grade according to the grading policy.

Round your course grade to two decimal places.

Since your grade is not actually rounded for this course, remove all decimals from your course grade.

To accomplish these tasks, use a combination of casting, Math.round(...), and basic math operations.

Determine if you received a plus or a minus attached to your grade, such as a "B+" or "A-". Refer to the
grading policy for these cutoffs (they are the same
for each letter grade).

Think about how you would use a boolean expression to determine each of these cases.

When you done with this extension, you must be cleared by the TA to receive credit.

Commit all your work to your repository

Fill in the form below with the relevant information

Have a TA check your work

The TA should check your work and then fill in his or her name

Click OK while the TA watches

If you request propagation, it does not happen immediately,
but should be posted in the next day or so

This demo box is for extension 1.10

Last name

WUSTL Key

Propagate?

(or your numeric ID)

Do not propagate

e.g.

Smith

j.smith

1

Copy from 1 to all others

2

Copy from 2 to all others

TA:
Password:

End of extension 10

Extension 11: Baseball Statistics Calculator (3 points):

Authors

Brennan Morell

Jarett Gross

St. Louis is a baseball city. Not too familiar with the game? No worries.
You will be able to successfully complete this lab and take away the same skills without any background knowledge.
However, if you’re new to the game and would like some background information, you may find the following video useful:

In baseball, batting average is used to represent the frequency a given player gets a hit.

Batting average is calculated by diving a player's hits by at-bats.

For simplicity, to determine whether a player is worthy of being an All-Star, define
a boolean allStarWorthy and assign its value
by determining whether or not the player has had
more than 200 at-bats and has a batting
average of at least 0.270.

The results of your studio session are to be reported and documented
in a file that you save in your workspace. You are to commit
that report prior to leaving studio. In the descriptions of
the studio exercises, verbs like report and document are
indications of activities you should summarize and discuss in your report.

In your groups, take turns documenting results, looking over shoulders, and
staffing the keyboard.

It is unacceptable to copy anything without understanding it. At any point,
the TA or instructor can point to something you've done and ask you why
it works, or change it and ask what would happen with the modification.

To receive credit for a studio, your team must
cleared by a TA using the green box at the bottom of this page.

Be careful how you use the web. You are required to develop solutions
as a group by thinking not by finding solutions that have been thought
out by others. You must be able to explain anything that you have done.

Warmup

First, form a group:

If you are at a table with a large, wall-mounted screens, a group of 3-4 people is fine.

If you are seated at a table without a large screen, a group of 2 people is better.

All but one member of your group should have this web page open so you can follow along
and see the instructions as you work.

All members of the group should update their repositories:

Open your repository in eclipse

Right-click (control-click on a mac) on your repository name

Drag down to Team...

Choose Update

Supply your WUSTL key and password as necessary

Plan to have one computer at which your team does its work. Initially,
one of you will be in charge of typing at that computer.

Throughout the studio, you should trade who is in charge of the keyboard. Before doing so,
commit your work to make sure your work is saved.

Procedure

This studio compares the monthly cost of renting vs. owning a home in the St. Louis area

The following tasks will test your knowledge of

Creating a class

Getting input from user

Printing to the console

Understanding primitive types

Utilizing Math.round

Sample Values:

Name

Vanguard Crossing

Zip Code

63104

Rent

600

Utilities

110.55

Mortgage

973.13

Task 0

Create a HomeOwning class in the __ package of the __ folder

Task 1

Prompt the user for the following inputs:

the name of the apartment complex

the zip code of the apartment

Consider the implications of using a double for the zip code versus a string.
Will the zip code be involved with any calculations?

the monthly rent of the apartment

the monthly utilities cost of the apartment

In banking and other activities with large quantities of money,
doubles are not advised because in Java the type double estimates for values.

the mortgage on the house

Sample output based on the example provided:

Vanguard Crossing is located in the Zip Code 63104

Task 2

What is the rent for an entire year?

What is the mortgage for an entire year?

Sample output based on the example provided:

Rent: 7200.0
Mortgage: 11677.56

Task 3
Given that there are 52 weeks in a year,

What is the rent for a week?

What is the mortgage for a week?

Sample output based on the example provided:

Rent: 138.46153846153845
Mortgage: 224.56846153846152

Task 4

Round your answers in task 4 to the nearest cent.

Sample output based on the example provided:

Rent: 138.46
Mortgage: 224.57

Task 5

Using the values given in the instructions, if someone decides to move to Red City Hill Apartments which has a rent of $730 a month,

How much percentage more will he or she be paying?

Round the percentage to the nearest tenth

Sample output based on the example provided:

The Rent will be 21.7% more.

Task 6

Using the values given in the instructions, if someone decides to move to a new house with a mortgage of $823.32 a month,

How much percentage less would he or she be paying?

Round the percentage to the nearest tenth

Sample output based on the example provided:

The Rent will be 15.4% less.

Task 7

If Utilities were $110.55 a month,

Would it be cheaper to rent or buy per month compared to the first house?

Would it be cheaper to rent or buy per month compared to the second house?

When you done with this extension, you must be cleared by the TA to receive credit.

Commit all your work to your repository

Fill in the form below with the relevant information

Have a TA check your work

The TA should check your work and then fill in his or her name

Click OK while the TA watches

If you request propagation, it does not happen immediately,
but should be posted in the next day or so

This demo box is for extension 1.12

Last name

WUSTL Key

Propagate?

(or your numeric ID)

Do not propagate

e.g.

Smith

j.smith

1

Copy from 1 to all others

2

Copy from 2 to all others

TA:
Password:

End of extension 12

Extension 100: Speed Limit Extension (C++) (5 points):

Authors

Dan Nolan

Issues:
Under development. Do not do this yet!

This extension is based on the Speed Limit Extension from Java, your task is the same but to code it in C++

You will calculate the fine one would have to pay for going over the speed limit in the state of Massachusetts: Massachusetts DMV.

By completing this work, you demonstrate that you can:

Create a C++ source file on your own

Arrange for the executable to take inputs of interest

Compute output values of interest

Produce meaningful output based on your computations

Have you ever received a ticket for speeding? If so, how do you feel about it? Were you going more or less than 10 miles over the speed limit?
The objective of this extension is not only to allow you to practice assignment statements and Data Types but also to allow you to create a
practical tool which could be used in everyday life.

Consider the following story: Your friend Joe is driving his Mini Cooper at 75MPH on a causeway that has the speed limit of 60MPH and he gets pulled over. Joe doesn't have a clue how much he is going to get fined because
he is both under the pressure of talking to the police officer and doesn't know how speeding fines are computed.
The officer does know how fines are computed. After the officer gets in his car, he considers Joe's speed and considers the speed limit and then gives Joe a fine.

Take a moment to think about the things the officer needs in order to compute the fine that Joe
will have to pay.

Procedure

First, create a speedLimit C++ source file in the
speeding package of the extensions source folder.

Think about the information you need to know to determine if someone is going above the speed limit.
You should also think about which Data Type you should use for your information.

You will need to prompt the user for inputs.

For input, use the following code just after the main method declaration:

cin >> speedLimit;

After you have finished that part, you have made your program able to take inputs, which you must later ask for.

Say you want to prompt for the speed limit and save the answer the user gives:
A way to do this would be writing an assignment statement, which you learned how to do in this module. Do you remember what part of the assignment statement executes first? Right or left?
If you don't, you should review this part of the module because you will need it to complete this extension.

Once you know which part of the assignment statement executes first, you can prompt the user for their input. Think about the Data Type you want the user to be able to input first though. Do you want them to input a decimal? An integer? A String?

Once you know which Data Type you want the user to input, you use the cin statement, variable of data type you want the user to enter.

For example, say you want to accept an integer, otherwise known as int. Asking the user for input would look like this:
int speedLimit;
cout << "Input speed limit: ";
cin >> speedLimit;

Arrange for your program to produce output such that:

For the first 10 miles over the speed limit, the fine is 50 no matter what

For any additional mile past the first ten, 10 dollars are added to the fine

Beware: Make sure your program works for logical inputs and doesn't fine you if you're going 0 miles per hour.

Finally, your program should print how many miles you were going over the speed limit and how much money the fine will be.To receive full credit be sure that the TA can clearly see your program is working correctly on a number of inputs.

When you done with this extension, you must be cleared by the TA to receive credit.

Commit all your work to your repository

Fill in the form below with the relevant information

Have a TA check your work

The TA should check your work and then fill in his or her name

Click OK while the TA watches

If you request propagation, it does not happen immediately,
but should be posted in the next day or so

This demo box is for extension 1.100

Last name

WUSTL Key

Propagate?

(or your numeric ID)

Do not propagate

e.g.

Smith

j.smith

1

Copy from 1 to all others

2

Copy from 2 to all others

TA:
Password:

End of extension 100

Extension 400: Expected Value (C++) (5 points):

Authors

Dan Nolan

Issues:
Under development. Do not do this yet!

Background

How do you feel about money, risk, and job satisfaction?
In this extension you will
examine some simple yet powerful ideas from economics, and you will
write code to compute how a person should behave based how he or she
views risk, reward, and job satisfaction.

The concepts we explore are as follows:

Utility

Utility
is an economic term referring to the total satisfaction you
derive or receive from some action or activity.

Given the choice of two activities and absent any other
concerns, a rational person would chose the activity
that yielded the higher utility.

Expected Value

If there is uncertainty about outcomes, then the expected
value of a given outcome is the product of its probability of occurring and
the value of achieving that outcome.

Let's consider the following two examples:

You are given $1. The probability of this event is 1, and your
value for achieving the outcome is $1, so your expected value is $1.

You enter into a (no-cost) lottery with 9,999 other people for a chance to win
$10,000. If the probability of the winner is uniformly distributed among those
who enter the lottery, you win $10,000 with probabilty 0.0001 and you lose (win $0)
with probability 0.9999. The expected value computation for this
scenario is as follows:

(.0001 × $10,000) &plus; (.9999 × $0)

Your expected value here is therefore also $1.

Based only on expected value, a person confronted with a choice on the
above two scenarios would have no reason to pick one over the other, since
the expected value is the same.

Now suppose the money given to you for certain
in the first scenario is doubled to $2. A rational person would surely
pick $2 over the lottery entry, because $2 is twice the expected value of
the lottery outcome.

However, we know there are people who would choose entering the lottery over
receiving a sure $1 or $2.

In the Powerball Lottery,
your chances of winning are
1 in 175,223,510. So a rational person shouldn't buy a ticket if the jackpot
is under $175M.
But allegedly rational people do buy tickets for jackpots under that
threshold.

How can we account for this behavior?
Read on.

Expected Utility Theory

The above analysis assumes a linear value for wealth.
We can account
for those who favor or avoid risk using
Expected Utility Theory.
This theory admits that rational people may have nonlinear views of
wealth. This means that you may like $1,000 more (or less) than 1,000 times as much
as you like $1.
Let's look at three examples:

Expected utility function

Notes

u(d) = d

Linear value of wealth. The above analysis applies to such
a person. NOTE TO SELF: 2nd derivative 0 here

u(d) = d2

This person values $10,000 the same way a linear
person would value $100,000,000.

In
the scenario given above, this explains why a person would enter the
lottery. The person's perceived value of winning $10,000 is
NOTE TO SELF: show the application of u here
$10,0002=$100,000,000, which at probability 0.0001 yields an expected
utility of $10,000: far greater than the $1 given for certain.

An alternate view is that this person has a linear view of wealth
(u(d)=d)
but an
unrealistic view of the probability of winning. For example, if this
person holds the false belief that the probability of winning is 0.1 instead
of .0001, then
the expected value jumps
from $1 to $1,000 using a linear function for expected utility.
Because economists try to model human behavior assuming rationality, they
translate this inflated view of luck into a nonlinear view of wealth.

Thus, the function u(d)=d2 captures a form of
risk-loving behavior.
More generally, when viewed from below, any convex function,
of which u(d)=d2 is an example, models risk-loving behavior.
NOTE TO SELF: 2nd derivative is positive

Such a person is either more certain of winning than
probabilities would indicate, or alternatively has a convex expected
utility function.

u(d) = sqrt(d)

On the other hand, this concave function captures risk-averse
behavior. In the lottery scenario, a win of $10,000 would feel like a win
of only $100 to this person. With a .0001 probability of winning, the
expected utility under this function is only 1 cent. Such a person would
not enter the lottery even if the no-risk payoff were reduced from $1 to 2 cents.
NOTE TO SELF: 2nd derivateive is negative here

Problem

Suppose you are trying to decide between one of the following
two careers:

Gamer

You join a start-up company, which is exciting and
could have high pay-off, but this venture might
fail.
Let's say
you succeed with probability p, and if so you will
earn $190,000. But if you fail (with probability 1-p), you earn only $5000.

Programmer

This job has no risk, and offers a salary in the range
of $110,000 to $160,000. Your salary will be determined by a random
choice of a value drawn uniformly from that range.

Let's begin by assuming you have linear value for money. Based on
the above description, write a program that does the following:

Prompts the user for a value for p, which is the probability of
the game start-up venture succeeding. The text of your prompt should
be a meaningful message.

Think about the type of p. Also what is a good variable name
for this concept?

Given p, compute the expected value of the gamer-job outcome.

Again, think about the type you need to represent the computed value,
and think of a good name for this concept.

Now pick a salary for the programming job by choosing a value
uniformly between $110,000 and $160,000.

Print both outcomes and a message that indicates whether you should
accept the gamer job over the programmer job for this particular calculation.
Such output might resemble:

Gamer: $97,500
Programmer: $115,000
You should be a gamer and not a programmer? false

Run your program for multiple values of p to be sure that your output
makes sense.

Nutrition Analyzer

In this extension you develop a simple tool that prints nutrition information about
food. This lab is based on what you learned in studio and in the lab. By completing this
extension you demonstrate that you can:

Create a C++ source file on your own

Arrange for the class to take inputs of interest

Compute output values of interest

Produce meaningful output based on your computations

Procedure

Create a Nutrition C++ source file in the lab1 package
of the labs source folder.

The lab1 class is currently empty, but don't let that bother you.
Right (control) click on lab1 and create a new source file called
Nutrition.

Arrange for your program to accept the following inputs:

name

The name of this food, provided as a String

carbs

The number of grams of carbohydrates in this food

fat

The number of grams of fat in this food

protein

The number of grams of protein in this food

statedCals

The number of calories stated on this food's label

For example, the values for a Snicker bar are:

name

Snickers

carbs

34.5

fat

13.6

protein

4.3

statedCals

271

At this point, you should be thinking about the data types you would use to represent each of the above
items. We tell you that the name is a String, but what about the other inputs?

The above example is provided to inspire your thinking.

To accept the inputs, use the same code we used in studio. Just after the main method declaration,
you should have the lines:

cout << "Please input food name: ";
string foodName;
cin >> foodName;

This will likely show an error because eclipse doesn't know about cin and cout. Do you remember how to
fix this? Ask if you need help.

After that, you should initialize your inputs using code modeled after the code you read and wrote in studio.

Arrange for your program to produce output such as the following:

Snickers has
34.5 grams of carbohydrates = 138.0 Calories
13.6 grams of fat = 122.4 Calories
4.3 grams of protein = 17.2 Calories
This food is said to have 271 (available) Calories.
With 6.6 unavailable Calories, this food has 1.65 grams of fiber
Approximately
50.9% of your food is carbohydrates
45.2% of your food is fat
6.3% of your food is protein
This food is acceptable for a low-carb diet? false
This food is acceptable for a low-fat diet? false
By coin flip, you should eat this food? true

Notes:

There are 4 Calories in a gram of carbohydrates or protein.

There are 9 Calories in a gram of fat.

The stated caloric content of some foods may be less than the value you obtain by adding the calories
due to carbohydrates, fat, and protein. This is because some of the carbohydrates may be dietary fiber, and
as such they are
unavailable for your body to use as energy.

In the above example, based on carbohydrates, fat, and protein, the food contains 277.6 Calories. However,
the label claims a modest 271 Calories. Thus, 6.6 Calories are unavailable and are attributed to dietary fiber.

From this we can compute 6.6 / 4 = 1.65 grams of the stated carbohydrates are fiber.

The percentages shown in the output above feature at most a single digit of precision after the decimal point.

You must arrange for your percentages to exactly this precise. This will take some thought, but it can be done
using what is taught in the book: int operations, double operations, casting, and
floor included in the cmath header.

You are not allowed to use printf or other functions you may
find that would accomplish this task. You have to figure out how to do it
using what you have learned in this module.

A food is a low-carb food if no more than 25% of its calories come from carbohydrates.

A food is a low-fat food if no more than 15% of its calories come from fat.

For the output lines whose conclusions are true or false, define an appropriately named
boolean variable in your program and set it equal to the expression that determines its value.

When you print the value it will print as true or false.

To accomplish the coin flip, recall the random-number generator with rand. Define
a boolean heads and assign its value
by comparing a
random number with 0.5.

Your strings can include the character sequences \t and \n, which have the effect of inserting a tab and a newline, respectively.
A tab will cause the output to shift right to a predetermined position.
A newline will end the current line of output and begin a new line.

To demo your lab, find some food labels (for real or on the web) and run your program with the appropriate values for those foods.

When you done with this extension, you must be cleared by the TA to receive credit.

Commit all your work to your repository

Fill in the form below with the relevant information

Have a TA check your work

The TA should check your work and then fill in his or her name

Click OK while the TA watches

If you request propagation, it does not happen immediately,
but should be posted in the next day or so