Wednesday, July 23, 2014

Fun with Python : Interactive Python - "Stopwatch: The Game"

Mini-project description - "Stopwatch: The Game"

Let's combining text drawing in the canvas with timers to build a simple digital stopwatch that keeps track of the time in tenths of a second. The stopwatch should contain "Start", "Stop" and "Reset" buttons.

Mini-project development process

1. Construct a timer with an associated interval of 0.1 seconds whose event handler increments a global integer. (Remember that create_timer takes the interval specified in milliseconds.) This integer will keep track of the time in tenths of seconds. Test your timer by printing this global integer to the console. Use the CodeSkulptor reset button in the blue menu bar to terminate your program and stop the timer and its print statements. Important: Do not use floating point numbers to keep track of tenths of a second! While it's certainly possible to get it working, the imprecision of floating point can make your life miserable. Use an integer instead, i.e., 12 represent 1.2 seconds.

2. Write the event handler function for the canvas that draws the current time (simply as an integer, you should not worry about formatting it yet) in the middle of the canvas. Remember that you will need to convert the current time into a string using str before drawing it.

3. Add "Start" and "Stop" buttons whose event handlers start and stop the timer. Next, add a "Reset" button that stops the timer and reset the current time to zero. The stopwatch should be stopped when the frame opens.

4. Next, write a helper function format(t) that returns a string of the form A:BC.D where A, C and D are digits in the range 0-9 and B is in the range 0-5. Test this function independent of your project. Note that the string returned by your helper function format should always correctly include leading zeros. For example
  • format(0) = 0:00.0
  • format(11) = 0:01.1
  • format(321) = 0:32.1
  • format(613) = 1:01.3

Hint: Use integer division and remainder (modular arithmetic) to extract various digits for the formatted time from the global integer timer.

5. Insert a call to the format function into your draw handler to complete the stopwatch. (Note that the stopwatch need only work correctly up to 10 minutes, beyond that its behavior is your choice.)

6. Finally, to turn your stopwatch into a test of reflexes, add to two numerical counters that keep track of the number of times that you have stopped the watch and how many times you manage to stop the watch on a whole second (1.0, 2.0, 3.0, etc.). These counters should be drawn in the upper right-hand part of the stopwatch canvas in the form "x/y" where x is the number of successful stops and y is number of total stops. My best effort at this simple game is around a 25% success rate.

7. Add code to ensure that hitting the "Stop" button when the timer is already stopped does not change your score. We suggest that you add a global Boolean variable that is True when the stopwatch is running and False when the stopwatch is stopped. You can then use this value to determine whether to update the score when the "Stop" button is pressed.

8. Modify "Reset" so as to set these numbers back to zero when clicked.

Steps 1-3 and 5-7 above are relatively straightforward. However, step 4 requires some adept use of integer division and modular arithmetic. So, we again emphasize that you build and debug the helper function format(t) separately

Answer: Access my code here 

Friday, June 13, 2014

The Fluidity of Keynesian Economics

Keynesian economics is the view that in the short run, especially during recessions, economic output is strongly influenced by aggregate demand. In the Keynesian view, aggregate demand does not necessarily equal the productive capacity of the economy; instead, it is influenced by a host of factors and sometimes behaves erratically, affecting production, employment, and inflation. 

The theories forming the basis of Keynesian economics were first presented by the British economist John Maynard Keynes in his book, The General Theory of Employment, Interest and Money, published in 1936, during the Great Depression. Keynes contrasted his approach to the aggregate supply-focused 'classical' economics that preceded his book. The interpretations of Keynes that followed are contentious and several schools of economic thought claim his legacy.

Keynesian economists often argue that private sector decisions sometimes lead to inefficient macroeconomic outcomes which require active policy responses by the public sector, in particular, monetary policy actions by the central bank and fiscal policy actions by the government, in order to stabilize output over the business cycle. Keynesian economics advocates a mixed economy – predominantly private sector, but with a role for government intervention during recessions.
Keynesian economics served as the standard economic model in the developed nations during the later part of the Great Depression, World War II, and the post-war economic expansion, though it lost some influence following the oil shock and resulting stagflation of the 1970s.

Theory 
Keynes argued that the solution to the Great Depression was to stimulate the economy  through some combination of two approaches:
# A reduction in interest rates, and
# Government investment in infrastructure .
By reducing the interest rate at which the central bank lends money to commercial banks, the government sends a signal to commercial banks that they should do the same for their customers.
Investment by government in infrastructure injects income into the economy by creating business opportunity, employment and demand and reversing the effects of the aforementioned imbalance.

Concept   

Wages and spending    
During the Great Depression, the classical theory attributed mass unemployment to high and rigid real wages.
To Keynes, the determination of wages is more complicated. First, he argued that it is not real but nominal wages that are set in negotiations between employers and workers, as opposed to a barter relationship. Second, nominal wage cuts would be difficult to put into effect because of laws and wage contracts. Even classical economists admitted that these exist; unlike Keynes, they advocated abolishing minimum wages, unions, and long-term contracts, increasing labour market flexibility. However, to Keynes, people will resist nominal wage reductions, even without unions, until they see other wages falling and a general fall of prices.

Active fiscal policy    
Classical economists have traditionally yearned for balanced government budgets. Keynesians, on the other hand, believe this would exacerbate the underlying problem: following either the expansionary policy or the contractionary policy would raise saving  and thus lower the demand for both products and labour. For example, Keynesians would advise tax cuts instead.

"Multiplier effect" and interest rates    
Two aspects of Keynes's model has implications for policy:
First, there is the "Keynesian multiplier", first developed by Richard F. Kahn in 1931. Exogenous increases in spending, such as an increase in government outlays, increases total spending by a multiple of that increase. A government could stimulate a great deal of new production with a modest outlay if:
# The people who receive this money then spend most on consumption goods and save the rest.
# This extra spending allows businesses to hire more people and pay them, which in turn allows a further increase in consumer spending.

This process continues. At each step, the increase in spending is smaller than in the previous step, so that the multiplier process tapers off and allows the attainment of an equilibrium. This story is modified and moderated if we move beyond a "closed economy" and bring in the role of taxation: The rise in imports and tax payments at each step reduces the amount of induced consumer spending and the size of the multiplier effect.

Second, Keynes re-analyzed the effect of the interest rate on investment. In the classical model, the supply of funds  determines the amount of fixed business investment. That is, under the classical model, since all savings are placed in banks, and all business investors in need of borrowed funds go to banks, the amount of savings determines the amount that is available to invest. Under Keynes's model, the amount of investment is determined independently by long-term profit expectations and, to a lesser extent, the interest rate. The latter opens the possibility of regulating the economy through money supply changes, via monetary policy.

New Classical Macroeconomics criticisms  
Another influential school of thought was based on the Lucas critique of Keynesian economics. This called for greater consistency with microeconomic theory and rationality, and in particular emphasized the idea of rational expectations. Lucas and others argued that Keynesian economics required remarkably foolish and short-sighted behavior from people, which totally contradicted the economic understanding of their behavior at a micro level. New classical economics introduced a set of macroeconomic theories that were based on optimising microeconomic behavior. These models have been developed into the Real Business Cycle Theory, which argues that business cycle fluctuations can to a large extent be accounted for by real  shocks.

New classical theorists demanded that macroeconomics be grounded on the same foundations as microeconomic theory, profit-maximizing firms and rational, utility-maximizing consumers.

The result of this shift in methodology produced several important divergences from Keynesian Macroeconomics:
# Independence of Consumption and current Income
# Irrelevance of Current Profits to Investment
# Long run independence of inflation and unemployment
# The inability of monetary policy to stabilize output
# Irrelevance of Taxes and Budget Deficits to Consumption

Tuesday, June 3, 2014

Fun with Python : Interactive Python - “Guess The Number” Game

“Guess the number” game
One of the simplest two-player games is “Guess the number”. The first player thinks of a secret number in some known range while the second player attempts to guess the number. After each guess, the first player answers either “Higher”, “Lower” or “Correct!” depending on whether the secret number is higher, lower or equal to the guess. In this project, you will build a simple interactive program in Python where the computer will take the role of the first player while you play as the second player.
You will interact with your program using an input field and several buttons. For this project, we will ignore the canvas and print the computer's responses in the console. Building an initial version of your project that prints information in the console is a development strategy that you should use in later projects as well. Focusing on getting the logic of the program correct before trying to make it display the information in some “nice” way on the canvas usually saves lots of time since debugging logic errors in graphical output can be tricky.
Mini-project development process
A basic template for this mini-project here (http://www.codeskulptor.org/#examples-guess_the_number_template.py). Suggested development strategy for the basic version of “Guess the number” is:

1. Decide on a set of global variables that contain the state of the game. For example, one obvious choice is the secret number that has been generated by the program. You will need other global variables, especially to accommodate later extensions to the basic game.
2. Figure out how to generate a random secret number in a given range, low to high. When discussing ranges, we will follow the standard Python convention of including the low end of the range and excluding the high end of the range, which can be expressed mathematically as [low, high). So, [0, 3) means all of the numbers starting at 0 up to, but not including 3. In other words 0, 1, and 2. We suggest using the range [0, 100) in your first implementation. Hint: look at the functions in the random module to figure out how to easily select such a random number. We suggest testing this in a separate CodeSkulptor tab before adding code to your project.
3. Figure out how to create an input text box using the simplegui module. You will use this input to get the guess from the user. For all variants of the game, this input field should always be active (in other words, a game should always be in progress). Again, test in a separate CodeSkulptor tab before adding code to your project.
4. Write the event handler input_guess(guess) that takes the input guess, compares it to the secret number and prints out the appropriate response. Remember that guess is a string so you will need to convert it into a number before testing it against the secret number. Hint: We have showed you how to convert strings to numbers in the lectures.
5. Test your code by playing multiple games of “Guess the number” with a fixed range. At this point, you will need to re-run your program between each game (using the CodeSkulptor “Run” button).
6. Fill in your new_game() function so the generation of the secret number is now done inside this function. That is, calling new_game() should compute a random secret number and assign it to a global variable. You can now call the function new_game() in the body of your code right before you start your frame.
From this minimal working version of “Guess the number”, the rest of this project consists of adding extra functionality to your project. There are two improvements that you will need to make to get full credit:
1. Using function(s) in the simplegui module, add buttons to restart the game so that you don't need to repeatedly click “Run” in CodeSkulptor to play multiple games. You should add two buttons: “Range: 0 - 100” and “Range: 0 - 1000” that allow the player to choose different ranges for the secret number. Using either of these buttons should restart the game and print out an appropriate message. They should work at any time during the game. In our implementation, the event handler for each button set the desired range for the secret number (as a global variable) and then call new_game to reset the secret number in the desired range.
As you play “Guess the number”, you might notice that a good strategy is to maintain an interval that consists of the highest guess that is “Lower” than the secret number and the lowest guess that is “Higher” than the secret number. A good choice for the next guess is the number that is the average of these two numbers. The answer for this new guess then allows you to figure a new interval that contains the secret number and that is half as large. For example, if the secret number is in the range [0, 100), it is a good idea to guess 50. If the answer is "Higher", the secret number must be in the range [51, 100). It is then a good idea to guess 75 and so on. This technique of successively narrowing the range corresponds to a well-known computer algorithm known as binary search.
2. Your final addition to “Guess the number” will be to restrict the player to a limited number of guesses. After each guess, your program should include in its output the number of remaining guesses. Once the player has used up those guesses, they lose, the game prints out an appropriate message, and a new game immediately starts.
Since the strategy above for playing “Guess the number” approximately halves the range of possible secret numbers after each guess, any secret number in the range [low, high) can always be found in at most n guesses where n is the smallest integer such that 2 ** n >= high - low + 1. For the range [0, 100), n is seven. For the range [0, 1000), n is ten. In our implementation, the function new_game() set the number of allowed guess to seven when the range is [0, 100) or to ten when the range is [0, 1000). For more of a challenge, you may compute n from low and high using the functions math.log and math.ceil in the math module.
When your program starts, the game should immediately begin in range [0, 100). When the game ends (because the player either wins or runs out of guesses), a new game with the same range as the last one should immediately begin by calling new_game(). Whenever the player
clicks one of the range buttons, the current game should stop and a new game with the selected range should begin.
Grading — 11 pts total
Here is a break down of the scoring:
1 pt — The game starts immediately when the “Run” button in CodeSkulptor is pressed.
1 pt — A game is always in progress. Finishing one game immediately starts another in the same range.
1 pt — The game reads guess from the input field and correctly prints it out.
3 pts — The game correctly plays “Guess the number” with the range [0, 100) and prints understandable output messages to the console. Play three complete games: 1 pt for each correct game.
2 pts — The game includes two buttons that allow the user to select the range [0, 100) or the range [0, 1000) for the secret number. These buttons correctly change the range and print an appropriate message. (1 pt per button.)
2 pts — The game restricts the player to a finite number of guesses and correctly terminates the game when these guesses are exhausted. Award 1 pt if the number of remaining guesses is printed, but the game does not terminate correctly.
1 pt — The game varies the number of allowed guesses based on the range of the secret number — seven guesses for range [0, 100), ten guesses for range [0, 1000).
To help aid you in gauging what a full credit project might look like, the video lecture on the “Guess the number” project includes a demonstration of our implementation of this project. You do not need to validate that the input number is in the correct range. (For this game, that responsibility should fall on the player.)

Answer :  Access my code here

Monday, June 2, 2014

A Modern Take on Diamond - Water Paradox

The paradox of value  which is also known as the 'Diamond - Water Paradox' is the apparent contradiction that, although water is on the whole more useful, in terms of survival, than diamonds, diamonds command a higher price in the market. The philosopher Adam Smith is often considered to be the classic presenter of this paradox. Nicolaus Copernicus, John Locke, John Law and others had previously tried to explain the disparity.

Labor theory of value 
In a passage of Adam Smith's An Inquiry into the Nature and Causes of the Wealth of Nations, he discusses the concepts of value in use and value in exchange, and notices how they tend to differ:

Furthermore, he explained the value in exchange as being determined by labor:

Hence, Smith denied a necessary relationship between price and utility. Price on this view was related to a factor of production  and not to the point of view of the consumer. The best practical example of this is saffron - the most expensive spice - here much of its value derives from both the low yield from growing it and the disproportionate amount of labor required to extract it. Proponents of the labor theory of value saw that as the resolution of the paradox.
The labor theory of value has lost popularity in mainstream economics and has been replaced by the theory of marginal utility.

Marginalism 
The theory of marginal utility, which is based on the subjective theory of value, says that the price at which an object trades in the market is determined neither by how much labor was exerted in its production, as in the labor theory of value, nor on how useful it is on a whole . Rather, its price is determined by its marginal utility. The marginal utility of a good is derived from its most important use to a person. So, if someone possesses a good, he will use it to satisfy some need or want. Which one? Naturally, the one that takes highest-priority. Eugen von Böhm-Bawerk illustrated this with the example of a farmer having five sacks of grain.

With the first, he will make bread to survive. With the second, he will make more bread, in order to be strong enough to work. With the next, he will feed his farm animals. The next is used to make whisky, and the last one he feeds to the pigeons. If one of those bags is stolen, he will not reduce each of those activities by one-fifth; instead he will stop feeding the pigeons.
So the value of the fifth bag of grain is equal to the satisfaction he gets from feeding the pigeons. If he sells that bag and neglects the pigeons, his least productive use of the remaining grain is to make whisky, so the value of a fourth bag of grain is the value of his whisky. Only if he loses four bags of grain will he start eating less; that is the most productive use of his grain. The last bag of grain is worth his life.

In explaining the diamond-water paradox, marginalists explain that it is not the total usefulness of diamonds or water that matters, but the usefulness of each unit of water or diamonds. It is true that the total utility of water to people is tremendous, because they need it to survive. However, since water is in such large supply in the world, the marginal utility of water is low. In other words, each additional unit of water that becomes available can be applied to less urgent uses as more urgent uses for water are satisfied.

Therefore, any particular unit of water becomes worth less to people as the supply of water increases. On the other hand, diamonds are in much lower supply. They are of such low supply that the usefulness of one diamond is greater than the usefulness of one glass of water, which is in abundant supply. Thus, diamonds are worth more to people. Therefore, those who want diamonds are willing to pay a higher price for one diamond than for one glass of water, and sellers of diamonds ask a price for one diamond that is higher than for one glass of water.

Efficiency model 
The Chinese economist Tan Lidong addresses the question through relative Economic efficiency. noting water is in such large supply in the world, but in the desert water-taking efficiency is very low, so the value of water is also high. If someone can invent high efficiency equipment to get water in the desert, by then the water would be cheap. He avers that value is determined by efficiency, as well as efficiency affected by tools, labor and resources.
He suggests we can calculate the exact value of the water or the diamond by using efficiency. He takes a historical approach to value, that exchange ratios have been known for many products for a very long time, and established by custom and practice. Technological change changes the efficiency of production, thus changing the relative values.

Criticisms  
George Stigler has argued that Smith's statement of the paradox is flawed, since it consisted of a comparison between heterogeneous goods, and such comparison would have required using the concept of marginal utility of income. And since this concept was not known in Smith's time, then the value in use and value in exchange judgement may be meaningless:
The paradox; that value in exchange may exceed or fall short of value in use was, strictly speaking, a meaningless statement, for Smith had no basis  on which he could compare such heterogeneous quantities. On any reasonable interpretation, moreover, Smith's statement that value in use could be less than value in exchange was clearly a moral judgment, not shared by the possessors of diamonds. To avoid not being able to compare money and utility, one may interpret Smith to mean that the ratio of values of two commodities is not equal to the ratio of their total utilities. Or, alternatively, that the ratio of the prices of two commodities is not equal to the ratio of their total utilities; but this also requires an illegitimate selection of units: The price of what quantity of diamonds is to be compared with the price of one gallon of water?

Differential Equations In A Nutshell

A derivative is the rate of change of one quantity with respect to another; for example, the rate at which an object’s velocity changes with respect to time (compare to slope). Such rates of change show up frequently in everyday life. For example, the compound interest law states that the velocity of interest accumulation is proportional to the principal account value, given by dV(t)/dt=rV(t) and V(0)=P, where P is the initial (principal) account value, V(t), a function of time, is the current account value (on which interest is continuously assessed), and r is the interest rate (dt is an instantaneous time interval, dV(t) is the infinitesimal amount by which V(t) changes in this time, and their quotient is the accumulation rate). Although credit card interest is typically compounded daily and described by the APR, annual percentage rate, this differential equation can be solved to give the continuous solution V(t) = Pe^(rt). 




1) Define derivative. Derivative (also called differential quotient; especially British) - the limit of the ratio of the increment of a function (generally y) to the increment of a variable (generally x) in that function, as the latter tends to 0; the instantaneous change of one quantity with respect to another, as velocity, which is the instantaneous change of distance with respect to time. Compare first derivative, and second derivative:[1]
  • First derivative – the derivative of a function, example: "Velocity is the first derivative of distance with respect to time."
  • Second derivative – the derivative of the derivative of a function, example: "Acceleration is the second derivative of distance with respect to time."  

2) Know the order and degree of the differential equation. The order of a differential equation is determined by the highest order derivative; the degree is determined by the highest power on a variable. For example, the differential equation shown in Figure 1 is of second-order, third-degree.

3) Know the difference between a general, or complete solution versus a particular solution. A complete solution contains a number of arbitrary constants equal to the order the equation. (To solve an nth order differential equation, you have to perform n integrations, and each time you integrate, you have to introduce an arbitrary constant.) For example, in the compound interest law, the differential equation dy/dt=ky is of order 1, and its complete solution y = ce^(kt) has exactly 1 arbitrary constant. A particular solution is obtained by assigning particular values to the constants in the general solution.

Sunday, June 1, 2014

Control of Mobile Robots - - Week 1 Exercise

You got a score of 4.00 out of 5.00.

Question 1

One way of getting a general feeling for what a differential equation is up to is to look at the sign and magnitude of the derivative at different points for different values of x. Use this idea for the dynamics

x˙(t)=x(t)3.

Which one of the plots below (where t is on the ``x-axis" and x(t) is on the ``y-axis") was generated by this system? Note that x(0)=10.
Your Answer


_image_



_image_




_image_
Correct 1.00
_image_


_image_






Question ExplanationThe first thing to check is what the axes and the initial condition for each plot is; in our case, these are plots of x(t) that start at x0=10. Thus, the correct plot will (at least initially) have a negative rate of change (x˙(0)=1000 to be exact). Working through using process of elimination we find the correct plot.

Question 2

One way of modeling epidemics is to describe how the fraction of infected individuals evolves over time. Let I be that fraction, with the model being

I˙=βI(1I)ρI.

Here, the constants β and ρ are the infection and recovery rates, respectively. What are the possible equilibrium points to this system (values for I when the fraction of infected individuals is not changing)?
Your Answer
Score Explanation
When I=0 or I=(βρ)/β Correct 1.00
Only when I=(βρ)/β


When I=0 or I=(1β)/ρ


Only when I=(1β)/ρ


Only when I=0


Total
1.00 / 1.00
Question ExplanationWe need to see what happens when I(t) does not change, i.e., when I˙=0. So, solve βI(1I)ρI=0. This is a 2nd-order polynomial equation, which means it has two solutions (although the two solutions may be the same).

Question 3

If someone gives you a possible solution to a differential equation, one of the checks needed to see if this is indeed a solution is by taking the required number of derivatives and seeing if the proposed solution does in fact satisfy the differential equation. Let

x¨(t)=ω2x(t).

Which of the following options is not a possible solution to this equation?
Your Answer
Score Explanation
x(t)=0


x(t)=cos(ωt)


x(t)=eωt Correct 1.00
x(t)=sin(ωt)


x(t)=ωsin(ωt)cos(ωt)


Total
1.00 / 1.00
Question ExplanationPlugging in each function and differentiating twice we get a second derivative that is not the same as the function in the question for one of the choices.

Question 4

We saw that the model of a cruise-controller could be given by

x˙=cmuγx,

where u is the input, x is the speed of the car, and c,m,γ are constant parameters. If there was no wind resistance in the cruise-control model (γ=0), what would the steady-state values be for the velocity x when using a pure D-regulator, i.e., when u=ke˙=k(r˙x˙)=kx˙ (since r is constant)?
Your Answer
Score Explanation
x()=0


x()=r


x()>r


Impossible to say


x() less than r Inorrect 0.00
Total
0.00 / 1.00
Question ExplanationPlugging in our choice of controller u=kx˙ and γ=0 as well we get: x˙=kcmx˙, which is no longer a differential equation. Think in terms of discrete time: xk+1=xk+dt``x˙′′ but what is x˙ now? And how can we determine x now?

Question 5

Let a discrete-time system be given by

xk+1=max{0,5xk}.

If this system starts at x0=10, what happens to the state of the system?
Your Answer
Score Explanation
It keeps switching between 0 and -5


It keeps growing from 10 up to


It jumps down to x1=0 and increases up by one until x5=5 and then jumps back to 0 again (and the process repeats)


It keeps switching between 0 and 5 Correct 1.00
It jumps down to x1=0 and remains at 0 for ever


Total
1.00 / 1.00
Question ExplanationStart by plugging in x0=10. Find x1. Keep plugging in, using this discrete update rule, until you see the pattern start to repeat. Be careful -- it's easy to make simple mistakes in your addition!