30 Eylül 2012 Pazar

Bursa Malaysia Shares Outlook september 24-28 2012

To contact us Click HERE
Indonesia stock info - Bursa Malaysia Shares Outlook september 24-28 2012 ;Share prices on Bursa Malaysia is expected to undergo a correction next week with the FBM KLCI confined within 1,600 and 1,620 points, dealers said.A series of bearish reports, which included back-to-back negative economic data from US and Europe and, China's manufacturing data which dipped to a three-year low, could see the local bourse coming in for consolidation.

"Given the local stock run over the past 12 months, we believe the local stock may do corrective movement next week," said Affin Investment Bank Vice-President, Head of Retail Research, Dr Nazri Khan.

He told Bernama that despite the short-term dips, the medium-term looked promising as there were some resilience with the local stocks recouping earlier losses and was still holding above the 1,620 points support level.

"Investors are now waiting and wondering when China and other Group of Seven countries will act to boost the market.

"In fact, we view the latest boost of bigger-than-expected US$127 billion in asset purchases from the Bank of Japan as a positive surprise for investors and hence opens out a possibility of more coordinated central bank action to boost the global economy.

"We are currently pegging 1,620 and 1,600 as support levels while resistance stands at 1,640 and 1,650," he added.

For the week just-ended, the FBM KLCI finished 2.62 points lower at 1,640.33 against last Friday's 1,642.95.

The Finance Index lost 160.58 points to 14,602.62, Industrial Index declined 6.29 points to 2,812.71 and the Plantation Index erased 187.86 points to 8,279.28.

The FBM Emas Index trimmed 126.94 points to 11,048.67, the FBM Mid 70 Index fell 134.24 points to 11,982.13 and the FBM Ace dipped 25.34 points to 4,328.48.

The weekly volume fell to 3.85 billion units, valued at RM6.99 billion, from 4.73 billion shares, valued at RM8.52 billion, recorded last Friday.

Main market volume decreased to 2.73 billion units worth RM6.84 billion from 3.34 billion units valued at RM8.29 billion registered previously.

Volume on the ACE market declined to 911.53 million units, worth RM130.84 million, from 1.1 billion shares worth RM204.74 million transacted last week.

Feel free to forward this Op Ed and follow our Blog stock market news today

Related Post:

How will impact US. President election on stock market 2013-2016

To contact us Click HERE
Indonesia stock info ; How will impact US. President election on stock market 2013-2016 : “2013 is gonna be a bummer,” warns Bloomberg BusinessWeek. “Whether it’s Barack Obama or Mitt Romney ... someone will have the misfortune of overseeing an economy” with “low growth, persistently high unemployment and huge amounts of debt.”
Worse, the magazine’s poll of 79 economists warns GDP growth will fall further, to 2.1%, with a real “chance the U.S. will be in recession.”

Flash forward through 2016: Politicians still warring, spending billions on re-elections. Recession? Yes. And Wall Street losing another 20% in the new presidential term.

How? Remember, between 2000 and 2010 Wall Street lost an inflation-adjusted 20% of the retirement portfolios of 95 million Americans as the Dow swung violently between a bottom of 6,470 and a top of 14,164. And it’ll do it again this decade, according to many reports we’ve covered in recent years predicting down markets this decade, probably before the end of the next presidential term.

Why? As BusinessWeek put it, economic trends are so bad, “fixing them will be beyond the immediate grasp of an Obama or Romney administration.” You must plan on a recession, inflation, retirement losses, higher taxes.

So what’s your best investment strategy? Get defensive — you’ll have ride out economic storms and bigger political wars the next four years, driving markets down.
10 reasons Wall Street stocks lose another 20% by 2016

Seriously, folks, why bet on the Wall Street casinos again? Didn’t work last decade. Why trust their relentless propaganda? Why bet on a losing game when the house always wins thanks to high fees and high-frequency trading? They’ll repeat the losses of the last decade in a world far more dangerous for investors than it was in the “Lost Decade” of 2000-2010.

If you do buy, consider the stock’s fundamentals, but also factor in the added negative impact of these 10 interrelated macro trends that further guarantee Wall Street will lose another 20% by 2020:

1. Totally dysfunctional Washington gets worse

No matter who wins, Romney or Obama, the war for the 2016 presidency will be far more destructive for America. The dysfunctional, no-compromise political battles will get more deadly for the country. This is behavioral economics at it’s egomaniacal worst: Former House Speaker Nancy Pelosi, a Democrat, admits Congress will continue divided. GOP strategist Karl Rove will start building an even bigger war chest starting New Year’s Day 2013. Billions. Democrats will match Rove dollar for dollar. Hostilities will accelerate.

BusinessWeek warns: “Obama likely won’t be able to pass more stimulus, and Romney will have a hard time lowering taxes. Neither campaign has a convincing growth strategy.” Both promise to reduce the deficit, “but the more likely effect of shrinking the deficit, through spending cuts and tax increases, will be to slow growth even further.

So count on four more years of political suicide as both parties become more aggressive, mean-spirited and hyper-irrational in a more costly, no-compromise, screw-America partisan war zone.

2. Wall Street has no moral conscience
Since 2008 Wall Street’s greed has been flaunted openly. Why? No restraints thanks to Treasury bailouts, Fed’s chap money, weak regulations, minimal prosecutions and Wall Street’s addiction to its own high-leverage, high-frequency derivatives casino that often generates $100 million profit days.

Investment bankers rule. Retail banking and investors are tolerated. Wall Streeters have no moral conscience. Their too-big-to-fail arrogance has put them above the law. It will get far worse. Only solution? Another 1929 crash. New Glass-Steagall.

3. Lobbyists keep fueling America’s ‘capitalist anarchy’

Forget democracy, America’s now a “capitalist anarchy,” thanks to the explosion of lobbyists running government. This trend shows no sign of abating. Imagine: 42,000 Washington lobbyists today, versus a handful in 1975. One expert estimates 261,000 special-interest “influence peddlers” throughout America.

The Center for Public Integrity reported that “more than 1,750 companies and organizations hired about 4,525 lobbyists, eight for each member of Congress, to influence health-reform bills in 2009.” America’s “capitalist anarchy” is loading the Treasury with deficits. And the debt is guaranteed to negatively impact future market returns.

4. Fed policies keep blowing a bigger bubble

Economist Marc Faber hits hard: “The world is heading toward a major crisis.” The coming collapse will be “caused by Federal Reserve Chairman Ben Bernanke and the Federal Reserve’s continuous printing of new money.” All the Fed’s bailouts, loans, credits and money printing since the 2008 Wall Street meltdown did “not create any long-lasting wealth or create healthy growth.”

These Fed policies began a couple decades ago with former Chairman Alan Greenspan’s free-market ideology funneling endless cheap money to prop up too-greedy-too-fail Wall Street banks. Now Bernanke’s blowing a new, bigger. more toxic credit bubble than 2008.

5. Trickle-down economics increasing inequality gap
In “The Price of Inequality,” Nobel economist Joseph Stiglitz tells us that “the American dream is a myth … the gap’s widening … the clear trend is one of concentration of income and wealth at the top.”

Huffington Post just reported on a “new study by the nonpartisan Congressional Research Service that has found that over the past 65 years” trickle-down economics does not work, “tax cuts for the rich have not led to economic growth and instead are linked to greater income inequality in the United States.” The study concludes: “Tax cuts for the bottom 90% of income earners can stimulate economic growth and job creation.”

But such facts are irrelevant to billionaires. Only a global catastrophe will shock them awake.

6. Foreign policy and a war of civilizations

The global investment world is far more volatile and dangerous today than in the Bush years. Witness the metastasizing rage triggered recently across the Arab world. America started a preemptive war of civilizations by attacking Iraq under false pretenses, one of the biggest foreign-policy blunders in American history.

That war had the unintended consequences of playing into the hands of our enemies, made them stronger, costing us trillions, weakening America as a military and global economic power. Now there’s no end in sight as anti-American rage spreads, inflaming the entire Arab world.

7. Perpetual growth economics destroying the planet

The classic economic principle of perpetual growth, once a given in economics and politics, is being challenged by “no-growth” research and principles of environmentalists who see most essential commodities as finite, nonrenewable planetary resources.

On one side, for example, energy producers in oil, coal, gas and alternative energy claim unlimited reserves for future growth in their sales, revenues and earnings. They dismiss claims by environmentalists about the unintended consequences of a global population increase of 50% by 2050 and the Earth’s inability to feed 10 billion people.

Nothing will change soon: Perpetual-growth myths win because energy companies lobbyists and campaign handlers have unlimited budgets to get energy-friendly politicians in office.

8. Clueless leaders: new meltdown inevitable
America is again being propelled to the edge of an economic cliff, already burdened with an estimated $29.7 trillion debt from the misguided political decisions of the past decade. Endless deficits lie ahead. Year-end fiscal negotiations will settle nothing, just kick core problems down the road.

The lessons of 2008 were never learned. As the authors of “This Time Is Different: 800 Years of Financial Folly.” put it: “The lesson of history is that even as institutions and policy makers improve, there will always be a temptation to stretch the limits ... the ability of governments and investors to delude themselves, giving rise to periodic bouts of euphoria that usually ends in tears, seems to have remained a constant.”

9. Next time, taxpayers won’t bail out Wall Street
I’ll bet you’re in total denial about this one. Congress avoids big decisions, till it’s too late. Moral-hazard critics warn that Wall Street’s arrogant too-greedy-to-fail bankers actually believe taxpayers will bail them out again when they trigger the next meltdown. Wrong.

Even if our politicians are dumb enough, Wall Street’s insatiable greed is a force pushing America into massive deficits and debt. Next time the resources simply will not be available to fund another bailout when the bomb goes off, the meltdown ignites.

So don’t listen to Wall Street’s casino croupiers, they’re playing a lethal game of liar’s poker with America’s future?

10. Casino odds guarantee you’ll just keep losing
Reminder: Between 2000 and 2010 Wall Street’s casino was in fact a loser’s game for Main Street investors. The Dow dropped below 6,400 in early 2002, later collapsed from a peak of 14,164 in 2007. Still, between 2000 and 2010 Wall Street lost an inflation-adjusted 20% of the retirement assets of 95 million investors.

Warning: Wall Street will repeat its failed performance, lose another 20% of your hard-earned money this decade. Their game’s fixed. Wall Street’s a loser.

Bottom line, Jack Bogle’s now warned that over 50% of Americans will never make it into a comfortable retirement. You’re stuck in Wall Street’s fantasy casino, a new version of Michael Lewis’s “Liar’s Poker” that’s just a recycled version of Charlie Ellis’ old “Loser’s Game.” In short, the odds are high they will lose a lot of your money again in the coming decade.

Why? No matter who wins the presidency, neither Obama nor Romney can fix America. Get ready folks, it’s really bad out there. It’ll be getting worse.


Feel free to forward this Op Ed and follow our Blog stock market news today

Related Post:

Asian stock markets fell september 26 2012

To contact us Click HERE
Indonesia stock info ; Asian stock markets fell september 26 2012 : Asian stock markets fell Wednesday after the worst sell-off in three months on Wall Street as pessimism about world growth spread across the Pacific.

Charles Plosser, president of the U.S. Federal Reserve's Philadelphia branch, told an audience that the Fed's efforts to support the world's biggest economy would likely fall short of its goals. That soured sentiment and sent Wall Street lower Tuesday.

Global stocks had risen earlier in the month as the Fed and other central banks came up with measures to boost sluggish growth. But optimism stemming from those moves has faded. Central banks had already bathed economies in massive stimulus through low interest rates and bond purchases but the world is still struggling to eke out growth, highlighting the limits of monetary policy.

Tensions between China and Japan, which are the world's second and third-biggest economies, have also knocked sentiment because of the risk it will affect trade.

Japan's Nikkei 225 stock average was down 1.6 per cent at 8,942.93 and Hong Kong's Hang Seng dropped 0.9 per cent to 20,525.17. South Korea's Kospi shed 0.6 per cent to 1,980.02 and Australia's S&P/ASX 200 fell 0.5 per cent to 4,351.90.

In Tokyo, export-dependent issues were sold on worries about the global economy and the continued strength of the yen, which erodes the earnings of such companies. Toyota shed 1.9 per cent and Murata Manufacturing Co. plunged 3.1 per cent.

Masahiro Yamaguchi, a vice-president at Mizuho Securities Co. in Tokyo said auto and other export issues were getting hurt because of worries about a slowdown in China, as well as the possible negative impact on exports from a simmering territorial dispute with China over tiny islands.

"It's about the China risk," he said. "The monetary policies are likely helping keep the drop in check, but they weren't enough to keep the rise going."

Political uncertainty in Japan was also adding to the cautious mood. The main opposition party is choosing a new chief later in the day. The candidates have more assertive policies than the administration in power, which could further deteriorate relations with China. The ruling party is expected to suffer a serious setback in the next parliamentary elections because of an unpopular tax increase.

On Wall Street, the Standard & Poor's 500 lost 15.30 points, its fourth straight decline, to close at 1,441.59. The 1.05 per cent drop was the worst for the S&P since June 25. The Dow Jones industrial average lost 101.37 points to close at 13,457.55.

In currency trading, the dollar fell to 77.75 yen from 77.70 yen late Tuesday. The euro rose to $1.2903 from $1.2898.

Benchmark crude was down 25 cents at $91.12 in electronic trading on the New York Mercantile Exchange.

Related Post:

Why Seoul shares KOSPI Down september 26 2012

To contact us Click HERE
Indonesia stock info - Why Seoul shares KOSPI Down september 26 2012 ;Seoul shares fell to their lowest levels in nearly two weeks on Wednesday, with some market participants saying that the correction could continue for the rest of the week as worries about the health of the global economy preoccupy investors.

Signs of slowing growth have taken centre stage again after equity markets rallied earlier this month on monetary easing measures taken by the U.S Federal Reserve and the Bank of Japan, as well as on the ECB's bond-buying plan.

Institutional investors joined foreigners in dumping stocks, with sentiment also hurt by protests in Spain that has underscored the country's financing difficulties.

"Despite ample liquidity in the market, investors remain concerned about whether economic fundamentals are really improving," Kim Hak-kyun, an analyst at Daewoo Securities.

The Korea Composite Stock Price Index (KOSPI) declined 0.6 percent to 1,979.06 points as of 0225 GMT, its lowest intraday level since Sept. 13. The KOSPI closed down 0.6 percent the previous day.

"The KOSPI is under pressure and is suffering a technical correction, and this is likely to continue this week," said Park Seok-hyun, an analyst at KTB Investment & Securities.

But Hyundai Motor, South Korea's second valuable stock after Samsung Electronics, bucked the trend, rebounding 1.8 percent.

Korea Investment & Securities said in a report that Hyundai gained market share in China in August, while its Japanese rivals suffered from falls, hurt by the territorial dispute between Japan and China.

Related Post:

why Groupon stock prices down september 25 2012

To contact us Click HERE
Indonesia stock info - why Groupon stock prices down september 25 2012 ; Shares of daily deal site Groupon plunged 7.21 percent, or 37 cents, on Tuesday, tripping a circuit breaker rule that protects stocks from being manipulated by short sellers.

Short sellers make money when a stock price goes down. The Nasdaq rule restricts prices at which a stock can be sold short.


Groupon’s stock, which had fallen as much as 10 percent earlier in the day Tuesday, closed at $4.82 a share.

The company’s stock has swung up and down as analysts weigh its efforts to diversify from the highly competitive and marketing-dependent daily deal strategy. The stock is down 76 percent from its public-offering debut price. Feel free to forward this Op Ed and follow our Blog stock market news today


Related Post:

29 Eylül 2012 Cumartesi

Quilt Patterns

To contact us Click HERE
Today we are going to talk about colorful abstract geometric patternssuch as quilts. For example, here is a beautiful hand-madequilt my sister Barbara Keenan created out of a variety of colorfulfabrics.

Certainly mathematicians are not the only ones to appreciate suchdesigns. Accordingto Wikipedia, peoplehave been making quilts at least since Renaissance times. Similargeometric designs also show up in architecture, oriental carpets andother art forms around the world. In part this comes from a deepseated human aesthetic appreciation for symmetry.

What is symmetry? Essentially it is a repetition in shape andcolor that our brains seem to enjoy, perhaps because it simplifieswhat would otherwise be a complicated jumble of unrelated visualelements. Most plants and animals have at least approximate left-rightmirror symmetry, so perhaps our brains evolved to notice symmetricforms because they help us interpret common scenes.

Barbara's fabric quilt is quite beautiful: one can enjoy looking at itfor an extended period of time, the eye following various paths,enjoying the contrasts between the black diamonds and the colorfultriangles. You can click the photo to see more detail.

What constitutes a visually "interesting" or "beautiful" pattern? Artists like my sister develop an intuitive understanding of what"looks" good, but is there a way to capture that intuition in moremathematical language?

After much searching, I read an interesting article on the webby NikosA. Salingaros called The "Life" of a Carpet: an Application ofthe Alexander Rules. While his focus is on Oriental Carpets, histheory and design guidelines apply much more generally. He provides adetailed description of the characteristics that make interestingdesigns.

We can find many of his ideas illustrated in Barbara's quilt. Some arepretty straightforward, like juxtaposing contrasts, e.g. a darkoutline around a light shape, such as her black diamonds and the outerblack border contrasting with the bands of colorful triangles.

Some of his other guidelines are more subtle, like the idea that thereshould be interesting detail at every distance scale, from the entirework down to very fine details. To my mind, one reason real quilts(and paintings) are more visually interesting than purely computergenerated geometric patterns is that fabric has texture and pattern ofits own. A small piece of fabric that forms a single triangle is oftennot one homogeneous color, but in fact a complex mix of colors andtextures on a much smaller, finer scale.

We see this too in Barbara's quilt. At the big-picture level, we havethe black diamonds against the colored diagonals. But within thecolored diagonals is a second layer of contrasts, this time mostly ofcolors (warm reds against cool blues) and values (dark against light),accentuated by the contrast in the orientation of the triangles.

The Carpet article also recommends including some randomness,but not too much. This also makes sense. A plot of random dots, linesor polygons looks like the visual equivalent of audio noise. This isnot surprising, since both have similar statistical properties. Incontrast, a modest amount of randomness - occasional deviations fromperfect symmetry - can actually add interest to a pattern.

Here too, the artist has done this intuitively. Part of the visualinterest in the quilt is that the colored triangles do not repeat inperfectly symmetric patterns, so that you keep coming back to them,looking for the pattern, catching glimpses of it but not quite fullyunderstanding its subtleties. There is symmetry at the high level; onecan imagine the pattern of black diamonds going on forever in alldirections; yet we would be hard pressed to say exactly what coloreach small triangle should be if we were to extend the design.

My children, who are much more musically talented than I, tell me thatthe same is true in classical music, where the listener comes toexpect certain patterns and can be pleasantly surprised when the musicoccasionally does something different.

A couple years ago, I decided to try out the design ideas inthe Carpet article by making a painting of a quilt-likepattern. I do not have the patience (or skill) to try actually sewinga quilt out of real fabric. As a prelude to painting, I wrote apattern generating program so I could experiment with some variations.

There are a large number of traditional quilt patterns, often formedby assembling right triangles of various colors into a square "block",and then repeating identical copies of that block in a grid layout,optionally rotating them to create different kinds of symmetries. Onevery interesting mathematical question is to try to enumerate, or atleast characterize, a wide variety of such patterns.

Mathematicianshave used group theory to classify repeating designs in theplane into 17 basic types calledWallpapergroups. However, when we allow patterns that do not repeatexactly (such as in our quilt picture) the possibilities are muchbroader, and I will not even begin to attempt a full description. Asjust the tip of the iceberg, let me point out that there are manyother ways to create geometric patterns besides using righttriangles. For instance, one can tile the plane using hexagons. Alsointeresting are patterns involving 5-sided shapes(e.g. PentagonalTesselations) and unusual configurations suchas Penrosetiling, in which two basic shapes can tile an arbitrarily largearea in a non-repeating (non-periodic) manner.

The "traditional" patterns have the advantage of simplicity:right triangles and squares are easy to draw and cut out without a lotof special measuring equipment or wasted fabric. Some of the "new"patterns (e.g. Penrose tiling) are a little more complicated, butshould I think be straightforward if one were to make a cardboardtemplate for each shape and then just trace them onto fabric.

I decided to stay within the traditional framework of righttriangles, but to try patterns that were not constrained by repeatingblocks, even though they should still involve some level ofsymmetry.

Computer generated patterns often look somewhat mechanical, e.g.

To me, this is not very interesting, aside from the novelty aspect: itwould be difficult to create this image as a fabric quilt, or as aconventional painting, because the visual impact depends so stronglyon the very precise, very mechanical progression in the colors.

My next step was to aim for images that looked more like traditionalquilts. I also experimented with adding randomness atvarious scales. Here are three example of designs I was able to create.

Ultimately, I decided that my painting would need morerandomness and less symmetry than these images. Actually making apainting is rather different from writing a computer program; you canmodify color as you go until it "looks right", and you can addtextures much like those of fabric. After a great deal ofexperimenting (and over-painting), the final result looked like this:

As you can see, I attempted to follow the guidelines of contrasts andrandomness at a variety of scales. You can judge for yourself whetherthe result is attractive.

I hope you enjoyed this article. While most of my posts are moretechnical, with source code to experiment with, I think it is fun tosometimes step back and enjoy the aesthetic side of math. To me, evenwithout "formulas", the images in this post are deeply mathematicaland quite intriguing. I certainly enjoyed creating my painting - it isfun to use a different side of the brain for a while! If you areinterested in these kinds of patterns, the links mentioned above arejust the beginning: there are a huge variety of web pages out therewith fascinating examples of periodic and non-periodic geometricpatterns described as Tesselations or Tilings.

As usual, please post questions, comments and other suggestions below,or email me directly at the address described at the end of theWelcome post. Remember you can sign up for email alerts about newposts by entering your address in the widget on the sidebar. Or follow@ingThruMath on Twitter to get a 'tweet' alerting you to each newpost. See you next time!

Supply, Demand and Market Microstructure

To contact us Click HERE
Today we are going to make an agent-based simulation modelof Supply and Demand. Pretend we have a room full ofpeople. Some of them have apples, some do not. Some are hungry, someare not. All have money in their pockets with which they can buy andsell apples, if they so choose. What determines the price of apples?

Much of conventional economic theory rests on the assumption ofperfectly competitive markets populated by perfectly rationalparticipants. If we let the people in the room interact by anopen-outcry auction, theory suggests they will listen to the bid andask prices, figure out where the supply and demand curves cross, andtrade the equilibrium quantity of apples at the equilibriumprice. This assumption greatly simplifies the mathematics, so much sothat it underlies almost all economic theory. But is this model ofhuman behavior realistic? Let's try some experiments!

Let me describe the background a little more clearly. We areinterested here in what academics call market microstructure:the magic of how prices actually get established on the scale ofindividual transactions. The thing being traded could be a piece offruit, a gadget like an ipod, an hour of professional services, or 100shares of Apple Computer on the stock market. The key point is thatnot everyone wants these things equally badly: a hungry person wantsan apple, but a person who just ate might rather have cash, so theycan buy a gadget instead. Moreover, not everyone has the same startingposition (or endowment): some people start the game holding anapple, while others do not.

As a result of this lack of symmetry, some people may wish tomake trades with other people. In our simple example, you can trademoney for apples and vice versa, but in a general equilibriummodel you can trade in a whole variety of different goods(e.g. oranges, lemons) simultaneously. In our simple example, everyoneis in the same place at the same time, but again, in a generalequilibrium model you can even have different locations and differenttime periods; you can interpret differences in price over time asinterest rates, and develop all kinds of deep insights into the realeconomy.

When economists first started trying to analyze markets, roughly acentury ago, there were no computers to do simulations, so they neededto make simplifying assumptions to reduce the problem to simplealgebra. As with theorems in math, there are a lot of technicaldetails you can include in the assumptions, and mathematicaleconomists have studied how much you need to assume in order to provethat people will act a certain way. For example,the Arrow- Debreu - McKenzie model, which is at the heart of generalequilibrium models in economics, requires certain technicalassumptions (e.g. convexity) in order to prove the existence of aunique equilibrium.

For today, though, let's keep it simple. Imagine that each person hasa secret reservation price at which they are indifferentbetween having an apple and having cash. For a hungry person, thisreservation price is higher than for someone who just ate. For astarving person, for whom this apple is their last hope of not dying,the price is essentially infinite: they will never give away theirapple if they start with one, and they will give away all of theirstarting cash to obtain one if they do not have one. For someone whois not hungry at all and who hates the taste of apples, the price isessentially zero: they will sell their original apple, if they haveone, for any positive price, and will never spend any of their moneybuying one.

Call the people who start the game with an apple sellers, andthe others buyers. The names reflect what they could do,but not necessarily what they want to do, nor even whatthey will do.

Let's walk through a version of the conventional theory. Imagine weline up all the sellers in increasing order of reservationprice. Also, line up the buyers in decreasing order ofreservation price. Now we walk down the line, exchanging apples,until the seller wants more than the corresponding buyer willoffer. For example, suppose the reservation prices look like this:

BuyersSellers
10 0.2
9 0.5
8 1.5
7 2.5
6 4.5
5 8.5
4 16
3
2
1

Nothing requires the number of buyers and sellers to match exactly.Here there are ten players who start off with an apple (potentialsellers), and seven who do not (potential buyers).

The first seller has a reservation price of 0.2 dollars, andthe first buyer has a reservation price of 10 dollars. Clearly theywould both be willing to make a trade, at any price between twenty centsand ten dollars.

The second pair (9, 0.5) are also willing to trade, as are the (8,1.5) pair,the (7,2.5) pair and the (6,4.5) pair. But they are a lot more specificabout what price is acceptable: in order for all of these pairs totrade, the price of apples must be between 4.50 and 6 dollars.

The remaining sellers want $8.50 or more, while the remaining buyers want to pay $5or less, so no further pairs will trade, regardless of whatprice we pick.

You have probably seen a diagram of intersecting supply anddemand curves as a way of visualizing the equilibrium. Here is aversion showing the data in the table above, where the horizontal axisrepresents people and the vertical axis their reservation price. Thered dots are sellers, the blue dots are buyers, and the thin graylines show the equilibrium price and volume. The equilibrium price isanywhere between 4.5 and 6 dollars, but if we had lots more players,each with randomly chosen reservation prices, the dots would mergeinto a continuous curve with a unique equilibrium price.

Notice that the equilibrium price is determined by where the linescross, not by any sort of "average" reservation price: changing thelast seller's reservation price from 16 to 32 would have no impact onthe equilibrium price or quantity. Economists refer to this phenomenonusing the word marginal: not in the usual English senses of"at the side of" or "unimportant", but rather tomean "incrementally" or "at the tipping point". The "marginalplayer" is the one in the center of the diagram, where thelines cross, who is essentially indifferent to buying or selling atthe equilibrium price.

Why does the theory predict this particular outcome? Theconventional argument for the emergence of the equilibrium price underperfect competition goes like this. Should someone in the market shoutout "the price is 8 dollars", more sellers would be interested, butfewer buyers. Presumably some of the sellers (those with reservationprices less than 8) would lower their price in order to win back thebuyers. Similarly, should someone claim "the price is 2 dollars",additional buyers would come to the table, but sellers would walkaway. This would encourage those buyers with high reservation pricesto raise their offers. In both cases, prices far from equilibriumwould trigger supply-demand imbalances that would nudge the playersback toward the equilibrium price.

In many ways, this is a very convincing story. However, it isa bit abstract. Economists use it to model all kinds of real worldmarkets; yet not all markets resemble an open-outcry auction. When yougo to a supermarket in the United States to buy groceries, postedprices are not subject to negotiation (although this is not the casewith automobiles, nor is it always true in othercountries). Supermarkets do compete with each other, and do advertiseprices in local newspapers, and shoppers can (if they have a car andenough spare time) drive to multiple stores to compareprices. Shoppers' reservation prices do vary - some people clipcoupons to ensure the best possible price, while others are relativelyprice insensitive. However, prices fluctuate a lot from day to day andstore to store. Prices in other markets can be even wilder: just thinkof the huge gyrations in the stock market in the last few weeks.

It is hard to imagine that this is all based on purelyrational calculations or to see it as a stable equilibrium situation.In recent years, many economists have begun looking at alternativetheories (e.g. behavioral economics) that attempt tobetter describe how real people behave.

This brings us to today's question: how well does the conventionalmodel fit reality? Or, to be more precise, since we will be doingcomputer simulations rather than experiments with live humans, we wantto know:
  • Can we design simple agents that achieve the equilibrium theory predicts?
  • Can we design plausible agents that fail to achieve the theoretical equilibrium?

In other words, for today, we are not trying todevelop prescriptive rules for how agents, orpeople, should behave. Instead, we are interested in studyingvarious descriptive theories: if people (represented bysimulated agents) behave a certain way, what happens?

We could undoubtedly construct complicated models that incorporate agreat many features of real market places. However, thequestion today is whether we can construct extremely simplemodels that capture enough realism to make the results interesting;the hope is that the simplicity of the models will help us ininterpreting why they behave the way they do.

Both questions (arguing for and against the conventional theory) areinteresting, and both can be answered affirmatively. Let's see what we can find out by experimenting withsimulations.

As before, we willuse Python and PyGame to implement theagent-based model and visualize the results. These are free,high-quality, open-source, cross-platform software packages that youcan grab from the web and install in just a couple of minutes. SeeAnEvolving Ecosystem Game for details on how to download them. Oncethese are installed, go to the Start Menu, under Programs look forPython 3.2, and within that, click on IDLE. Again, the previous posthas more details on how to get started using Python. I also highlyrecommend reading a tutorial suchas Introductionto Computer Science Using Python and PyGame to help you getstarted with these powerful tools.

Let's start with a (hopefully) plausible model thatillustrates how the theory can fail if its assumptions are not met. Wewill leave it as a challenge to readers to try constructing a "Simple"model that does match the theory.

We need to decide how to model the agents, how they should interact, and howto visualize the progress of the simulation.

The model: Each agent will have a starting endowment of zero orone apples, and a secret reservation price. Each time step we choose arandom agent A who will interact with a second random agent B. If Ahas an apple, A will offer B an ask price, i.e. a price atwhich A would be willing to sell. If A does not have an apple, A willoffer B a bid price, i.e. a price at which A would be willingto buy. A chooses the price randomly, either above her reservationprice (if she is selling) or below (if she is buying). Either way, ifB can and is willing to trade at the specified price, they do so. The gameends after 500 such interactions.

Here is the code. We define an Agent class that keeps track of thenumber of apples the agent owns, as well as their reservation price.We create our agents to match the table of Buyers and Sellersshown above, so we can compare to the theoretical outcome describedearlier.

import pygameimport randomrandom.seed(123456)class Agent:    def interactWith(self, other):        if self.apple == 0 and other.apple == 1:             # maybe buy from other            bid = random.uniform(0, self.price)            trade(bid, self, other, bid >= other.price)        elif self.apple == 1 and other.apple == 0:             # maybe sell to other            ask = random.uniform(self.price, maxPrice)            trade(ask, other, self, ask <= other.price)    def __init__(self, initialApples, reservationPrice):        self.apple = initialApples        self.price = reservationPricedef trade(price, buyer, seller, success):    global iter    iter += 1    if success:        line(green, buyer.price, seller.price)        dot(green, price, 7)        buyer.apple += 1        seller.apple -= 1        print("price: ", round(price, 3),               " seller: ", seller.price,               " buyer: ", buyer.price)    else:        dot(gray, price)    dot(blue, buyer.price)    dot(red, seller.price)    pygame.display.flip()def dot(color, price, r=4):    pygame.draw.circle(screen, color, (getX(),getY(price)), r)def line(color, p0, p1):    x = getX()    pygame.draw.line(screen, color, (x,getY(p0)), (x,getY(p1)), 2)def getX():    return round(iter*W/(nIter+1.))def getY(price):    # note (0,0) is TOP left of window    return round(H - H*price/(maxPrice+1.))W = 800; H = 500; nIter = 500; maxPrice = 24# initialize graphics window:pygame.init()screen = pygame.display.set_mode([W, H])pygame.display.set_caption("Supply and Demand")white = [255, 255, 255]; gray = [128, 128, 128]red = [255, 0, 0]; blue = [0, 0, 255]green = [0, 200, 0]; yellow = [255, 255, 0]screen.fill(white)pygame.draw.rect(screen, yellow, (0,getY(6),W,getY(4.5)-getY(6)))pygame.display.flip()# initialize agents:seq = [] # one-dimensional list of Agentsfor p in [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]:    seq.append(Agent(0, p)) # buyersfor p in [0.2, 0.5, 1.5, 2.5, 4.5, 8.5, 16]:    seq.append(Agent(1, p)) # sellers# main loop:iter = 0done = Falseclock = pygame.time.Clock()N = len(seq)while done==False:    if iter <= nIter:        a = seq[random.randint(0,N-1)]        b = seq[random.randint(0,N-1)]        a.interactWith(b)    clock.tick(120)    for event in pygame.event.get():        if event.type == pygame.QUIT:            done = Truepygame.quit()

Only a few lines in this long code listing really matter forour purposes. The first section (the Agent "class") specifies howthey interact with each other, and how to initialize them. The two"for" loops just before the "main" loop create 17 Agents matching thetable of buyers and sellers. Inside the main loop, we randomly selectagents A and B for interaction.

All the rest is just for implementing the graphical visualization. Asthe simulation progresses, we use the PyGame graphics features todisplay what is happening. There are many ways we could try tovisualize the progress; for today, I have decided to plot timeincreasing horizontally, with price increasing vertically. Red dotsshow seller reservation prices, blue dots show buyer reservationprices. Gray dots show suggested transaction prices, which turngreen (and get connected to the corresponding red and blue dots with agreen line) if the offer is accepted. We also print thedetails of successful trades for reference. The horizontal yellow barshows the price range predicted by the theory, namely 4.5 to 6dollars.

Here is a typical run.

price:  0.77  seller:  0.5  buyer:  10price:  1.48  seller:  0.2  buyer:  4price:  7.161  seller:  2.5  buyer:  9price:  2.198  seller:  1.5  buyer:  2.5price:  5.897  seller:  4.5  buyer:  8price:  4.396  seller:  4  buyer:  4.5price:  4.94  seller:  2.5  buyer:  5price:  5.899  seller:  4.5  buyer:  7price:  5.202  seller:  5  buyer:  6

Initially (near the left side) there are buyers (bidding in blue)spread over the whole range below $10. There are also sellers (askingin red) from very low prices all the way up to $16. In some cases,such as the seller whose reservation price is $16, they stay red thewhole game. But other sellers, with low reservation prices, wind upselling early on, after which they become potential buyers. Thus as wemove to the right of the image, several initially red horizontaltrails eventually turn blue once a sale occurs. Similarly,some early buyers with high reservation prices become sellers (bluechanges to red) after an early transaction.

It is even possible for the same agent to be a buyer in onetransaction and a seller in another. I deliberately made all thereservation prices distinct so that we could use them to refer to theagents unambiguously. Looking for the ".5"'s in the list oftransactions, we see that Agent 2.5, Agent 4.5, Agent 4 and Agent 5all play both buyer and seller roles. Their reservation prices aretoward the middle of the pack, so they can pretty easily buy or selldepending on who else they are dealing with.

The final quarter of the graph has no green dots. Bythis point, all of the apples are in the hands of the people with thehighest reservation prices, so nothing further will happen. This isquite remarkable. Indeed, it illustrates why free markets are oftena very effective method for redistributing goods.

Did we match the theory? No. Of the 9 transactions, the firstfour prices are well outside the yellow band. The last 5 do occurwithin (or at least quite close to) the yellow band predicted by thetheory, so we might think we are at least "approaching" equilibrium astime goes on. However, if we try running it again with a differentrandom seed (12345), we get different results, due to different randomdice rolls:

price:  1.52  seller:  1.5  buyer:  8price:  4.639  seller:  2.5  buyer:  7price:  3.045  seller:  0.5  buyer:  4price:  1.88  seller:  0.2  buyer:  10price:  5.557  seller:  4.5  buyer:  6price:  8.998  seller:  4  buyer:  9

This time only 2 of 6 transactions fall within the predicted band, andthe last transaction of all is well outside it. We do see the samebasic pattern of trades moving apples from those who do notwant them much to those who want them very much; by half way into thesimulation, all of the apples are once again in the hands ofthe people with the highest reservation prices (all the red dots areabove all the blue dots).

Why don't all the prices fall inside the yellow band? Doesthis contradict the theory? No. Ken Arrow and the others proved amathematical theorem: that if agents behave in certain ways(perfectly rational perfect competition with convexutilities), then they will indeed reach the equilibrium price.The theory is not wrong; indeed its authors won a Nobel Prize for it.But our simulated agents are neither particularly rational (they donot attempt to look ahead, game the system, or even keep track of pastencounters) nor particularly competitive (they do not negotiate withmore than one opponent at a time, nor do they adjust price in responseto what they learn). The theory is not applicable to our littleexperiment, because our agents do not behave the way the theoryassumes.

This leads me to offer a fun challenge to readers: canyou devise an alternative simulation in which agents do actaccording to the theory, trading the predicted quantity of apples andonly doing so at prices inside the yellow band?

One ground rule: do not actually make the agents line up inorder of their reservation prices, in the manner we used to derive thesupply and demand curves at the beginning of this article. Theirreservation prices are private, not written on their foreheads for allto see, and real market places usually do not have a "supervisor" liningpeople up this way.

The goal is to keep the simulation as simple as possible,adding only the minimal amount of extra complexity needed to get theagents to act "properly". They do not need to actually performcomplicated "rational" calculations in their heads, they just needto act as if they knew what they were doing.

If you like, please do submit suggested solutions (or even justideas for what you would like to try, even if you do not code themyourself). You can enter them directly into the Comments box below, orGoogle-mail them to me (at the address described at the end of theWelcomepost) and I will collect them for a subsequent follow-up article.

I hope you enjoyed this discussion. As usual, please postquestions, comments and other suggestions, or G-mail me directly. Remember you cansign up for email alerts about new posts by entering your address inthe widget on the sidebar. Or follow@ingThruMath on Twitter toget a 'tweet' for each newpost. About the Blog has some additional pointers for newcomers, who mayalso want to look atthe Contents page for a complete list of previous articles. See younext time!

Tracking Hurricane Irene

To contact us Click HERE
A friend of mine in the Boston area is avidly tracking Hurricane Irenevia the Internet. He sent me some great links to sites with charts andgraphs, which made me think about all the mathematical modeling thatgoes into storm forecasting these days. So, for anyone out there alsotracking the storm, here are some handy links, plus a discussion ofhow weather forecasting actually works mathematically.

This first image comes from Google'sCrisis Response service, which overlays "Google maps" with data from the National Weather Service and other sites. The actual site is interactive, so you can toggle on and off features like the forecasted path of the storm, and you can zoom in to see the locations of nearby Red Cross shelters and local Evacuation routes.

It turns out we can also get very detailed forecasts for things likewind speed. This next picture shows the National Weather Servicewind speed projections for Boston, hour by hour.

This image camefrom Boston.com,which has apparently extracted the National Weather Service forecastdata and put it into a nice graphical format where you can click toselect your city.

High winds can be damaging, but hurricanes can produce damagingflooding as well.

This third image comes fromTides and Currents at the National Oceanic and Atmospheric Administration (NOAA), which runs the National Weather Service. Again, the actual site is interactive, with forecasts and past history for a variety of locations.

This particular plot shows the actual water level versus the predictedlevel for this time of year (without a hurricane). The tides normallyproceed on a fairly smooth, roughly sinusoidal basis, since they aregoverned by the Moon revolving around the Earth. The red "observed"line is now more than a meter (3.5 feet) above the blue "predicted"line, and in fact that discrepancy has been rising steadily all day,as shown by the green line (observed minus predicted). In fact,although it is presently low tide, the water level is up whereit would normally be at high tide, so in a few hours when hightide naturally arrives, there could be flooding.

So how does the National Weather Service come up with all of this?Well, of course, it is all done "by computers", these days, but whatdoes that really mean?

Physicists long ago worked out a set of "partial differential equations"that describe fluid flow. Roughly speaking, think of a chunk of air,possibly encased inside an inflated balloon so you can visualizeit. Various forces act on the balloon, causing it to move around. Forinstance, gravity pulls it down, the wind can blow it, and soforth. The temperature matters as well, since hotair is less dense than cold air and hence will tend to rise. Themoisture content also matters, in part because rain and snow are verymuch in the category of things we want meteorologists toforecast.

We can capture the impact of these various forces in "partialdifferential equations". They are "partial" because the quantitiesof interest (temperature, pressure, wind speed, and so forth) arefunctions of not one but several variables: latitude, longitude,elevation and time. They are "differential" because they describethe change in these quantities over time (in calculus terms,they involve derivatives).

Unfortunately, partial differential equations (PDEs) are quitedifficult to solve, even with the aid of computers. A great deal ofacademic research in applied mathematics -including myown Ph.D. back in 1991 - goes into finding more accurate and efficient ways tosolve various kinds of PDEs using super-computers. The weather equations areparticularly difficult to solve, which is one of the reasons why it ishard to accurately forecast the weather more than a few days forward;this is connected to the fact that the weather equations describe aChaoticSystem.

One big hurdle is data. To really solve the weather equationsaccurately, we need to know the initial conditions. That means we needto know the temperature, pressure, wind speed, and so forth,at every place on Earth, not to mention everywhere abovethe Earth as well, at least up to heights where the air becomes thinand no longer plays much role in determining the weather. Of course,we do not know all these numbers. But, applying the resources ofgovernments around the world, the human race is these days able tocollect measurements of these quantities at a large number oflocations around the planet, on a frequent, automated and accuratebasis. This helps a lot.

Notice that even to forecast weather in the US, we needmeasurements from all over the globe, because weather systems movearound: the wind does not respect national boundaries.

The more money we spend (on monitoring additional sites), themore accurate the forecasts can be. However, more data also meansmore computer processing time is needed just to do the calculations,which is why weather forecasters are amongst the largest users ofsuper-computing facilities (right up there with code breakers,protein-folding biologists, and quantum chemists).

Think of a globe of the earth covered by a mesh of latitudeand longitude lines. If we use 24 longitude lines (one per time zone)and 24 latitude lines, we get a total of 576 regions: not squareshaped, since the surface of the Earth is curved, butquadrilaterals. Suppose we divide the atmosphere above us into 10layers; now we have 5760 three-dimensional "cells". Each of these islike a "balloon", in my earlier analogy, and the equations describewhat happens to the air inside it.

This is fine, except that each of these 5760 cells covers a huge chunkof the Earth's surface, on the order of the size of Texas. We wouldprobably prefer a more specific forecast, one that can tell us aboutthe weather in our own town, not just the "average" weather forhundreds of miles around us. The solution is clear: we need a finermesh.

So, suppose we double the mesh: we use twice as many longitude lines,twice as many latitude lines, and twice as many layersvertically. That gives us 8 times as many cells, which means thecomputer will take (at least) 8 times longer to crank through all thecalculations - and we will have to spend 8 times as much money tocollect all the data. But unfortunately, even the resulting 46,080cells are still rather large - much larger than typical cities, andlarger than many states. So, we need to repeat the "refinement"process and double the mesh again. Now we have 64 times as many cellsas we started with - with 64 times the cost and computer requirementsas well. Actually, the way the solution algorithms work, the computertime generally goes up faster than the problem size, so with 64 timesas many cells, the computer might need 128 times as long to work onit, or even more.

You see where this is going. To get the "cells" down to a reasonablyhuman size scale requires a huge number of cells, and a vastbudget for data collection and calculations. But the result is veryhandy: extremely detailed forecasts that take into account all mannerof local conditions, as illustrated by the images at the start of thisarticle.

Now consider what happens if it takes the computer 24 hours to crankout a forecast for 6 hours in the future.

That is a forecast that is 18 hours obsolete even when it first comesout of the computer!

This leads weather forecasters to use parallelcomputers. These are a special kind of super-computer thatessentially consists of a large number of ordinary computers ("nodes")connected together with a specially designed high speed network sothat they can communicate very rapidly. If you have 2 nodes, you mightlet one work on the equations for the cells in the NorthernHemisphere, and the other on the Southern. If you have 4 nodes, youcan also split East and West. And so on.

Of course, there is a potential problem with splitting up thecalculations this way. The weather near the equator is impacted byboth Northern and Southern Hemisphere cells, so somehow the two nodesneed to periodically communicate, exchanging information about theboundary or interface region. And since the weather in a day or two orthree may be influenced by the current conditions far away, we cannotsimply ignore the Southern Hemisphere portion of the calculation.

This exchange of data at the interfaces takes time, and the more nodesin our parallel super computer, the more time (on a percentage basis)gets "wasted" doing this communication, instead of doing the actualcalculations. That means that a parallel computer with 256 nodes willnot, in general, run 256 times faster than a single node: it mightonly achieve a "speedup" of 64, say, due to the overhead of constantlyhaving to exchange interface data between nearby nodes.

Finally, there is an element of probability in all ofthis. Since we lack complete initial data for the entire Earth, wehave to "guess" what the temperature, pressure, etc. are in-betweenthe various measurement stations. To the extent that we guessincorrectly, the forecasts will also be incorrect. So, we can trymaking several different guesses and seeing how much difference itmakes.

For instance, suppose I know the current temperature in Bostonis 60 degrees (Fahrenheit), and the temperature in New York is 70degrees, but I lack an observing station in Hartford (part way betweenNew York and Boston). I can guess that Hartford is 65 degrees, butperhaps it really is only 64, or 66, or something. So now, instead ofrunning my weather simulation once, I need to run it several times,with different guesses for Hartford, and then I can see how muchdifference it makes. This gets quite complicated, since I also have toguess the starting values for a lot of other places besides Hartford!Ultimately it is this sort of approach that enables the WeatherService to make quantitative predictions of form "there is a 30%chance of rain today in Hartford".

So, as you can see, there is a great deal of complexity (andcost) hidden behind all the wonderful charts and graphs we saw above.As usual, we have only scratched the surface. My hope is that regularreaders of this blog are getting a sense for the vast range ofquestions that mathematics can help answer.

I hope you enjoyed this discussion. As usual, please postquestions, comments and other suggestions, or G-mail me directly. Remember you cansign up for email alerts about new posts by entering your address inthe widget on the sidebar. Or follow@ingThruMath on Twitter toget a 'tweet' for each newpost. About the Blog has some additional pointers for newcomers, who mayalso want to look atthe Contents page for a complete list of previous articles. See younext time!

Why Monotonous Repetition is Unsatisfying

To contact us Click HERE
Today we have an article from Guest Author Nikos A. Salingaros, Professor of Mathematics, Urbanist & Architectural Theorist at the University of Texas at San Antonio.

As you may recall, I mentioned Nikosin QuiltPatterns, a couple of weeks ago. I had come across hisarticle The"Life" of a Carpet: an Application of the Alexander Rules, whichwas the best (most "mathematically" oriented) article I had found onthe web on the topic of what characteristics of a work of art make itaesthetically pleasing.

Roughly speaking, his idea is that people do not like monotonousrepetition, but neither do they like randomness. Instead, humansprefer "structured variation", patterns that have some degree ofsymmetry and hierarchy, but which also contain variation on multiplescales.

His article discussed "oriental" carpets, but clearly similar ideasapply to other decorative objects such as quilts. In fact, his ideas apply much more broadly, for instance to music: wedo not care for the monotonous repetition of a single tone, nor forrandom tones; instead, actual music is a carefully structured blend ofrepetition and variation.

After reading the Quilt article, Nikos contacted me, and after somediscussions, he has put together a new article, focusing onArchitecture (but again, much more widely applicable). I think you will enjoy it, as yet another take on this elusivequestion of how to describe mathematically what makes goodart. Here it is!


Why Monotonous Repetition is Unsatisfying

Nikos A. Salingaros, The University of Texas at San Antonio.

Conjectures on combinatorial complexity

When applying mathematics to interpret our world we invariably runinto formidable difficulties. Explaining human perception of oursurroundings and our reactions to the environment requires that weknow the mechanisms of our interaction with the world. Unfortunately,we don't -- not yet. Thus, explanations of why we react to differentforms in our environment tend to be conjectural.

We know from observation that human beings crave structured variationand complex spatial rhythms around them, but notrandomness. Monotonous regularity is perceived as alien, withreactions ranging from boredom to alarm. Traditional architecturefocuses on producing structured variation within a multiplicity ofsymmetries. Contemporary architecture, on the other hand, advocatesand builds structures at those two extremes: either random forms, ormonotonously repetitive ones. Let us explore why human beings find thelatter unappealing, and propose what they do like instead, with theultimate aim of characterizing that mathematically.

I present some ideas on design and the influence of certain structureson human perception. These questions arose in the context ofarchitecture and urbanism, yet the problem goes much deeper, intocombinatorics and human physiological response. Lacking a rigoroustheory that explains the phenomenon, I am offering some intuitiveresults in the hope that someone will pursue them further. I believethere exists a straightforward mathematical model for what is goingon.

The observed effect concerns modules repeating in a geometricallyregular manner: an application of translational symmetry. For example,consider identical rectangles lined up straight. On the scale ofskyscrapers, many of those buildings simply repeat the floor design(as seen on its side) vertically, so that the whole building showsvertical translation symmetry (Figure 1).

Figure 1. A skyscraper shows vertical repetition.

There are also countless examples of exact repetition of unitshorizontally, either identical structural elements within onebuilding's facade (Figure 2), or separate but identical buildingslined up straight along a road. A typical example is the repeatingmodular box making up an urban housing or office development (Figure3).

Figure 2. Non-traditional building showing horizontal repetition.

Figure 3. Identical modular buildings repeat along a street.

Many observers react negatively to such simplisticrepetition. And, apparently, our degree of unease increases as moreunits are seen to repeat. Identical objects perfectly lined upgenerate a feeling of discomfort in the viewer. At the very least, weexperience something mechanical to which we react negatively as humanbeings, since we are used to more natural structures with variationand complexity. Readers are encouraged to check thisassertion. Observations should be performed with the entire body in afull-scale environment: simply looking at pictures or at areduced-scale model fails to engage all of our perceptive apparatusand will not lead to useful results. The conjecture is that somethingfundamental is at play here that affects our perceptive mechanism,triggering a negative signal.

So, what do people prefer? And why? I open the can of worms ofarchitectural fashion by illustrating an older example of tallbuilding typology, dating from the end of the 19th to the beginning ofthe 20th centuries (Figure 4). Monotonous vertical repetition isabsent. In addition, a richness of articulation that is part oftraditional tectonics and ornamentation provides a hierarchy ofdecreasing scales.

Figure 4. Neo-Gothic skyscraper.

Even though architects since the 1920s advocate monotonous repetitionin tall buildings (Figure 1), it is not really appealing to mostpeople. I believe buildings with more complex yet ordered shapes makea far better city -- but then, they must also pay attention to thehuman scale (which is another topic for discussion).

Steps toward an explanation

First, the mathematics points us to the algorithmic complexity of theconfiguration. The simplest complexity measure considers thegenerating code of a configuration. Complexity can be measured asbeing directly proportional to the length of code (though this is initself a simplistic measure that does not apply in more sophisticatedsituations, it is sufficient here). In this case, repetition in onedirection is trivially simple, since the code for generating it is:"define a unit A, then align n identical copies along one direction toget AAAAAAAAA...". The generating code is trivial.

Second, why is human neurological response actually negative? Someinsight into the effect comes from the notion of Biophilia, whichasserts that our evolution formed our neurological system withinenvironments defined by a very high measure of a specific type ofcoherent complexity. That is, our neurological system was created(evolved) to respond directly and exquisitely to complex, fractal,hierarchical geometric environments. When placed in environments thathave opposite geometrical features, therefore, we feel ill atease. The theory is being verified by experiments: see the collectionof essays "Biophilic Design" edited by Stephen Kellert etal. Minimalist environments make us feel ill at ease. Simplisticrepetition is one such minimalistic geometrical setting in which wefind no algorithmic complexity, hence no visual and intellectualinterest. But our response is not simply to ignore it: we cannot, andit provokes anxiety in us.

Questions immediately arise, such as why does the feeling of uneaseincrease with the number of repetitions? Here is evidently astraightforward Combinatoric problem, if only we knew what the humanbrain is measuring or counting when looking at repeating modules. Butwe don't. One guess is that the feeling of unease grows not linearlybut exponentially with the number n of repeating modules. If the brainis counting permutations among identical units, or trying to labeleach unit, then the possible combinations increase exponentially. Itcould also be true that the brain is frustrated by trying to identifydistinct modular units so as to fix a coherent picture of itsenvironment -- necessary for survival and deciding upon afight-or-flight response. If the units are identical they cannot becatalogued in memory.

Some examples

In what environments does one encounter large-scale geometricalconfigurations with a lot of monotonous repetition? Actually, all suchexamples are human-made, being strictly the results of industrialproduction. I claim that simplistic repetition occurs neither innature, nor in pre-industrial human creations.

In nature, we almost never find simplistic repetition on themacroscopic scale. (Yes, pure crystals do have microscopic regularitybut that structure is not visible -- furthermore, naturally-occurringpure crystals are quite rare.) Inanimate physical structures almostalways have some variations that prevent the unpleasant monotonouseffect. For example, the most regular repetition I can immediatelythink of occurs in the hexagonal cells of honeybees and solidifiedlava flows (the Giant's Causeway); but in each of those cases therepetition occurs with abundant minor imperfections (Figure 5). Thosegeometries therefore avoid the "industrial" feeling of beingmonotonous. Looking at wild honeycombs is fascinating, and walking oncrystallized lava is as well. And neither of these structures is acommon part of our living environment. Other physical geometriesdefined by repetitions occur with a great deal of variation and soescape monotony.

Figure 5. Natural honeycomb.

Living structures with repetition show so much variation in therepetition that monotony is entirely avoided. Consider the leaves of atree: no two are identical, and their positioning combines adistribution based on the Fibonacci sequence with randomness due tothe growth of the tree branches as influenced by environmentalfactors. No simplistic repetition along a line here!

Large-scale hexagons have been used in buildings. Where an additionalvariation is introduced to distinguish the modules, the resultsucceeds, but where the modules repeat monotonously, the overalleffect is felt negatively. The architects of those buildings appearunaware of the effect of monotonous repetition, but then so manybuildings from the past one hundred years blatantly display monotonousrepetition, so it seems to be something desired rather than arrived ataccidentally. As the experience is not yet rigorously documented itcould be dismissed as personal opinion or preference. Nevertheless, Ibelieve this is NOT personal preference but instead the reaction ofour bodies, and is thus felt by the general population.

Avoiding Combinatorial Complexity

I introduced the notion of combinatorial complexity in the book"Twelve Lectures on Architecture". This is precisely the effect ofmonotonous repetition experienced in the environment. Two solutionswere given of how to avoid combinatorial complexity. Both solutionsinvolve breaking the translational symmetry in some way.

The first solution is to introduce symmetry breaking by means ofvariety in the repeating modules (Figure 6). Symmetry breaking is akey notion that comes from theoretical physics: one adds smalldifferences to an otherwise perfect symmetry. The configuration is NOTsymmetric unless we ignore those minor differences. Therefore, thereis approximate symmetry on the global scale but it does not extend tothe smaller scales. In the present example, we maintain thetranslational symmetry on the larger scale (the repetition of amodular unit), but introduce variations within each module so everymodule is only approximately the same. Strictly speaking, it's nolonger a module. These small variations are sufficient to affect ourperception of the whole configuration, however, changing it from beingmonotonous to interesting.

Figure 6. Columns with variety, spaced symmetrically.

The second solution is to group a few modules together into a clusterof no more than three or four (Figures 7 and 8). We somehow tie threeor four modules into a supermodule, which itself then repeats. What weare doing is in fact introducing a hierarchy where previously noneexisted. In the original repeating configuration of n modular units,the scales are only two: the module itself, and all the modules linedup filling the size of the entire configuration. By grouping modules,we define a new scale at the size of the grouping, not exactly threeor four modules large, because it includes modules plus anyintermediate spaces.

Figure 7. Grouping columns into clusters of three.

Figure 8. Grouping columns into clusters of four.

These two groupings establish a strong informational relation betweenwhat we initially considered to be the module and any spacesurrounding it; grouping columns with spaces links alternatingcontrasting units. Rhythm on both the architectural and urban scalesdepends upon the intricate interweaving of space and material, whichare treated on an equal design footing.

It is worth pointing out that these solutions come from traditionalarchitecture, and are seen to be re-invented repeatedly by differentcultures in history and in different geographical regions. Somethinginnate is driving humankind towards discovering and implementing thesesolutions, and it's not simply a matter of aesthetic preference. Alsonote that our modern industrial age (beginning, say, from the 1920s)is marked by its break with the architecture of the past by thedistinction of whether to pursue and celebrate monotonous repetition,versus avoiding it altogether. Since the effect produces unease in theuser, this raises serious questions about why architects and urbanistsmake it a point to generate it in their buildings.

Christopher Alexander's explanations

Christopher Alexander is a pioneer in investigating environmentalcomplexity and developing techniques for generating living geometry inthe built environment. By "living geometry" we mean a particularcomplexity that embodies coherence and which is perceived asphysiologically and psychologically positive by humanbeings. Alexander refers to the environmental effect as "healing",confirming the independent line of investigation coming fromBiophilia. Although not expressed in the present manner, Alexander'swork offers fundamental insight into the problem of monotonousrepetition.

Alexander has presented "Fifteen Fundamental Properties" that arefound in all coherent structures, comprising inanimate matter,biological structures, and especially in human-made objects andenvironments built before the industrial age. Those rules can beapplied to generate living environments today, and are clearly usefulin avoiding, or repairing, monotonous repetition so as to remove itsnegative effect. A reader can find descriptions of these properties inAlexander's "The Nature of Order. Book 1: The Phenomenon of Life", andmy own summary in "Twelve Lectures on Architecture". I describe threeof Alexander's properties here.

1. Levels of Scale postulates that stable structures contain ahierarchy of distinct scales, and those scales are carefully spaced sothat the scaling factor between two consecutive scales is very roughlyequal to three. This is a universal property satisfied, for example,by all fractals. (Whereas fractals exist with every scaling factor,Alexander postulates that hierarchies with scaling factor near threeare perceived as more natural). There should exist distinct scaleswell defined in the structure. The larger scales are related throughsome magnification (exact or approximate) to the smaller scales, usinga scaling factor. As described above, grouping repeating units intoclusters introduces intermediate scales where none existedinitially. As such, it is one solution to avoiding or repairingmonotonous repetition.

For example, what makes a colonnade informationally comfortabledepends just as much on hierarchy as on repetition. Inter-columnarspacing ranges from two column widths in some Classical temples, tofour in the nave arcade of a Basilica and in Roman colonnades, to sixin many Medieval Cloisters, to eight in Far Eastern traditionalarchitecture (with variations for individual cases). In all theseinstances, the space between columns defines the next higher scale,and repetition links two consecutive hierarchical scales. As a result,the columns and spaces are perceived togethercoherently. Twentieth-century architects introduced extremely thincolumns (called "pilotis" or stilts) and widened their separation sothe intervening space is more than twelve times the width of a column.

2. Alternating Repetition postulates that simple modules should notrepeat, but rather, it is paired contrasting modules that can doso. There are several consequences of this rule. The alternation ofunits leads to contrast, which introduces spatial rhythm (albeitprimitive but at least present, whereas monotonous repetition has nospatial rhythm at all) (Figure 9). Looking at natural, biological, andpre-industrial structures Alexander found alternating repetition to bewidespread, and noted that it was adopted as a technique for creatingstable configurations.

Figure 9. With smaller-scale insertions, windows become alternating.

Alternating repetition is directly related to the groupings discussedearlier. An alternating pattern ABABABABA really includessymmetric groupings on many distinct scales: ABA, BAB, ABABA, BABAB,etc. defined naturally through their bilateral symmetry. This wealthof subsymmetries is not evident in configurations with monotonousrepetition. For a discussion, see "The Nature of Order. Book 1: ThePhenomenon of Life". Even so, a configuration with alternatingrepetition but no further variations or groupings on higher scaleswill show monotonous repetition if it is large enough.

3. Gradients occur when the size of similar components decreases inone direction. Here is a solution that was not mentioned earlier inthis essay, and which breaks monotonous repetition: make all the unitsof different size, not randomly, but in a carefully controlled mannerso as to create a gradient. Then, the ensemble is perceived asharmonious and not unsettling. Translational symmetry is brokenbecause the units have decreasing lengths. Again, Alexander foundcountless examples of gradients in natural, biological, andpre-industrial structures.

Gradients prevent monotonous repetition, but in a different manner tosymmetry breaking. In the latter, the main symmetry is maintainedwhile symmetry is broken on smaller scales. Gradients, on the otherhand, break the symmetry on the original scale and do not necessarilydo anything on smaller scales.

Here I mentioned only three of Alexander's fifteen fundamentalproperties, yet there are other ones that bear directly and indirectlyupon our problem of monotonous repetition. All of this discussion isbut a small part of a general theory of design that uses recursivealgorithms [a good topic for a future paper in this series]. Assumingas axiomatic several geometrical properties found in nature, Alexanderhas formulated a method for designing and constructing complexsystems.

Interestingly, following Alexander's design method "The Theory ofCenters", one cannot get to monotonous repetition. It's not thatmonotonous repetition is forbidden in any ideological sense; ratherthe algorithmic design rules can never arrive at solutions thatdisplay monotonous repetition. That mechanical configuration, and mostother unnatural, anxiety-inducing geometries, resides outside thespace of solutions obtainable from the Theory of Centers. To reachmonotonous repetition, one has to abandon the design rules thatgenerate living structure. Therefore, since the Theory of Centers wasmost certainly followed by designers and builders of all traditionalcultures instinctively, this explains why we never see monotonousrepetition in traditional artifacts, buildings, and cities.

Symmetry breaking prevents informational collapse

An identically repeating module generates simplistic translationalsymmetry. As explained previously, such a configuration hasalgorithmically trivial complexity. From the information theory pointof view, the configuration is collapsible to its single module plusthe rule for repetition. Thus, the configuration as a whole has noinformational stability: it is prone to collapse. Symmetry breakingchanges this because it is no longer possible to condense the wholeinto a single repeating module.

There may be more to it than simple visual concerns about monotony indesign. A physical structure is only one of an enormous variety ofcomplex systems that run our universe. Each complex structure mustprotect itself against structural collapse, otherwise we will not findit around to observe. Does informational collapse parallel other, moresignificant mechanisms of systemic collapse? And do complex systemsfind analogous methods of avoiding systemic collapse?

Since symmetry breaking through the creation of higher-order groupingsgenerates a hierarchy, this itself is one basic feature of a stablesystem. By introducing distinct levels in a scaling hierarchy, thecomplex system distributes itself on different levels, and thus it isnot dependent solely upon one or two levels. Symmetry breaking as seenin nature and in traditional artifacts, buildings, and cities is notrandom, but serves to define an irreducible hierarchicalstructure. This question is discussed further in "Twelve Lectures onArchitecture".

Blending into the background and emotional nourishment

Natural environments are characterized by an enormous degree ofstructural complexity, yet for the most part, we perceive them asbackground. Our perceptive system is apparently wired to noticeanything that contrasts with a natural background. It signals alarmand makes us uneasy. Since natural environments are fractal, itfollows that non-fractal objects will stick out and be noticed byus. This includes pure Platonic forms (cubes, rectangular prisms,pyramids, spheres) that define just a single scale, the largestone. Usually, those repeating forms create the monotonous repetitioneffect discussed here.

Andrew Crompton sent me some helpful suggestions on the topic of thisessay: Human creations are designed either as neutral or picturesque,and traditional products are designed to vanish into oursurroundings. When we inhabit an environment, or surround ourselveswith human-made objects, we don't want any individual object to botherus -- that is, not to disrupt the sense of visual coherence we can drawfrom our complex environment. Repetitive buildings or buildingcomponents may be computationally boring, but they do imposethemselves upon our cognition by not blending into thebackground. They stick out. They do not scale (as I discussed earlier)so they do not fit into a traditional structural hierarchy of a citythat has evolved over generations.

Monotonous repetition disturbs us because it is unnatural; and is sobecause it fails to share geometrical features common in naturalcomplex structures. The phenomenon goes further, however, in that"blending into the background" is not a neutral effect, but definitelya regenerative one. Biophilia gives us emotional nourishment (withconcomitant physiological benefits) from a complex, coherentenvironment; therefore I am talking about positive effects.

Thoughts about contemporary architecture

In contemporary architecture, many practitioners have rebelled againstmonotonous repetition and have come up with their ownsolutions. Invariably, those solutions inject randomness into thetranslational symmetry in a way that leads away from coherence. Thisis the opposite from the solutions outlined above and implemented bytraditional architecture and urbanism, which seek coherence. Someonewho is familiar with contemporary architects' philosophy of wishing tobreak with the past at all costs should not be surprised thattraditional evolved solutions are not adopted, but that the oppositeeffect is sought.

The facades and plans of many contemporary buildings rely on modularunits that are for the most part monotonously repetitive. Thetranslational symmetry is sometimes broken by random changes, however,so that the overall effect is one of imbalance, irrationality, andlack of purpose (Figure 10). This negative impression is justifiedsince the architect simply introduces random changes for visualeffect, not for any structural or functional reason. The reaction ofthe user is not positive, because our body also reacts to randomnesswith alarm.

Figure 10. Randomness in a facade destroys coherence.

While the topic of contemporary design lies outside the presentinvestigation, those examples of fashionable architecture thatrandomize symmetry contrast sharply with the solutions describedhere. In general, architectural symmetry breaking as practiced todayviolates perfect symmetries (which could be a good thing) but on thewrong scale, so that the coherence of the ensemble is reduced insteadof enhanced (Figure 10).

Again the discussion goes back to our body's predilection for coherentcomplexity in our environment, and our negative reaction when builtforms deny it to us. In its search for design novelty, architecturalsymmetry breaking as seen in contemporary structures deliberatelyavoids creating the sought-for hierarchy of subsymmetries on distinctscales.

Conclusions

I claimed a visual effect of monotonous repetition and suggested thatit induces unease and even anxiety in viewers experiencing such astructure at full scale. Hopefully, researchers in environmentalpsychology will perform the necessary rigorous testing in order toestablish any effect such structures have on our psychology andphysiology. Looking for an explanation of this effect from mathematicsled me to conjecture some sort of combinatorial analysis that ourbrain engages in, the details of which are as yet unknown. The processof analyzing our environment occurs automatically because we need toposition our bodies within it informationally, and subconsciouslyjudge our safety from environmental threats. If an environmentembodies monotonous repetition, it could tire our neurological system,and that is possibly what creates a negative effect on ourbodies. This essay concluded with suggestions for avoiding the effectof monotonous repetition. Altogether, I believe this is a pretty butnot well-defined, hence woefully under-investigated mathematicalproblem.

References

Christopher Alexander (2001) The Nature of Order. Book 1: ThePhenomenon of Life, Center for Environmental Structure, Berkeley,California.

Stephen R. Kellert, Judith Heerwagen, and Martin Mador, editors (2008)Biophilic Design: the Theory, Science and Practice of BringingBuildings to Life, John Wiley, New York.

Nikos A. Salingaros (2010) Twelve Lectures on Architecture:Algorithmic Sustainable Design, Umbau-Verlag, Solingen, Germany.

Related reading

Allen Klinger and Nikos A. Salingaros (2000) A Pattern Measure,Environment and Planning B: Planning and Design, volume 27, pages537-547. Availablehere.

And there you have it. I hope you enjoyed this discussion.Nikos and I are hoping that someone out there will take these ideaseven further. For instance, the whole area of algorithmiccomposition (either of images or music) revolves around being able to convert ideas like those expressed above into algorithms for generating imagesand music. I would love to hear about any ideas readers might havealong these lines.

If you enjoyed this article, you might also like Koch Snowflakes or Algorithmic Art, for colorful designs incorporating some of these ideas.

As usual, please post questions, comments and other suggestions, or G-mail me directly. Remember you can sign up for email alerts about new posts by entering your address in the widget on the sidebar. Or follow@ingThruMath on Twitter toget a 'tweet' for each newpost. About the Blog has some additional pointers for newcomers, who mayalso want to look atthe Contents page for a complete list of previous articles. See younext time!

Random Walks and Gambler's Ruin

To contact us Click HERE
Suppose you have $100 and you decide to go to a casino to try to double your money. Are you better off putting the whole $100 on a single bet, or should you make a lot of smaller bets? Maybe you should adjust the size of your bet as the evening progresses? Should you stop as soon as you reach $200 (if you ever do), or keep going?

Lots of people have opinions about questions like these. Today, I will show you how to calculate the correct answers yourself with just a few lines of code in R. Even better, you will understand the approach, which means you can do your own analysis of whatever strategy you want to test. And best of all, it's free: no need to spend real money at an actual casino to find out.

First, you need a copy of R. This is the free, high quality,open source statistical programming language that has become astandard for statisticians in industry and academia because it is botheasy and powerful. Download the latest version for Windows, Mac, orLinux from The R Project forStatistical Computing. Click on "Download R" and select a mirror(meaning, pick a site located close to you, to speed up the downloadprocess - there are mirrors all over the world), then click "DownloadR for Windows" (or Mac or Linux). Then just double click the installerand accept the default selections. You should now have a desktop iconor Start menu entry for starting R. You can copy and paste the samplecode from this blog post right into the R console window, and it willprint answers and draw graphs right on your computer screen.

We are going to answer the questions by running simulations. Not thegiant computer-game kind of simulations, with photo-realistic images ofblackjack tables, just a simple mathematical simulation of theessential elements of the process.

What do we need to know to set up the simulation? Not very much. Wedon't even need to know the details of any particular casino game,just your probability of winning and your payoff if you dowin. These vary depending on the game you choose to play.

So, let's assume the following situation:
  • You start with some initial amount of money.
  • You choose a size for your next bet.
  • With probability w, you win back your bet plus more.
  • With probability 1-w, you lose your bet.
  • You decide whether to play again or to stop.
  • You have to stop if you cannot make a minimum bet.
Let 'm' represent how much money you have to play with. Let 'b'represent the amount you choose to bet, which must be between 0 and'm'. Let 'w' be the probability of winning, and let 's' be themultiple of your bet that you get if you win. In symbols:
  • With probability 'w', you now have 'm+b*s', because you get back your bet, bringing your total back to 'm', but then on top of that you get 's*b' as a prize.
  • With probability '1-w', you now have 'm-b', because you lose the amount 'b' that you bet.

We can code this up using R without difficulty. We have only tospecify the strategy you want to test. We can encapsulate yourstrategy into a function that returns the size of your nextbet, as long as we interpret a zero or negative bet size as meaningyou choose to end the game and walk away without further betting.

However, the questions at the beginning of this article asked whetheryou would be "better off" under certain strategies. This is trickierto decide, since it depends on your personal values (both moral andfinancial). In other words, the answer depends on you.

In order to have something to discuss here, I will rank orderthe strategies according to the probability that you do not losemoney. However, you can choose to rank them by other criteria, ifyou want, such as the average amount of money you walk away with. Happily,the results of our simulation will provide a complete picture of thepossible outcomes, so you can decide for yourself which strategy youprefer.

Here's the code. You can copy and paste this into R now.

w <- 0.48s <- 1f <- 0.5nextBet <- function(m) {  if(m >= 200) 0  else m*f}oneNight <- function() {  m <- 100  b <- nextBet(m)  while(b >= 1 & m >= b) {    if(runif(1) < w) m <- m + b*s    else m <- m - b    b <- nextBet(m)  }  m}score <- function() {  n <- 1e4  x <- 0  for(i in 1:n)    if(oneNight() >= 100) x <- x+1  x/n}print(score())

This should only take a second or two to run, after which it shouldprint a number around 0.37, which means that in about 37% of the testcases, the strategy did allow you to leave with at least as much moneyas you started with. But what exactly is the strategy we are testinghere?

Let's examine the code. The first line sets the probability of winningto be 48%. That's because in R, the two characters '<' and '-'together act like an arrow pointing left, and they mean "assign".

The next line sets s=1, which means you are playingdouble-or-nothing.

Finally, the strategy: 'f' represents the fraction of your currentbalance that you will bet each turn. In this example, 'f' is 1/2,which means that on your first turn, you bet $50, which is half yourbalance. If you lose, you will only have $50 left, so your second betwill be half of that, or $25. If you win, you will have $150, so yoursecond bet will be $75. And so on.

How does 'f' come to mean 'fraction to bet'? The answer is in the'nextBet' function. This function receives as an input your currentmoney balance 'm'. If you have reached $200, it returns zero, meaningtime to go home. Otherwise, it returns 'm*f', which is fraction 'f' ofyour current balance.

You can modify the code to test other strategies by changing the'nextBet' function. We will look at an example toward the end. Firstthough, let's see how 'nextBet' gets used. The 'oneNight' functionstarts you off with m=100 dollars. Then it calculates your initialbet. As long as that bet is positive, it draws a random number betweenzero and one using 'runif(1)', and if that is less than 'w', youwin. Winning raises your balance to 'm+b*s', while losing lowers it to'm-b'. Finally, you get to decide the size of your next bet; choosingzero means you exit the loop and are done. I have imposed a minimum bet of$1 here, so actually, if your balance drops below $2, half of it willbe below $1, so you will stop. I have also insisted that you haveenough money to cover the bet (that's the 'm >= b' condition in thewhile loop).

Calling the 'oneNight' function simulates a single night at thecasino. However, any one night could be lucky or unlucky, purely bychance, irrespective of the strategy you want to test. So the 'score'function calls 'oneNight' ten thousand times, to give a very thoroughevaluation of the possible results.

You can modify the 'score' function to reflect whatever metric youwant to use for ranking strategies. I have made it count up the numberof nights in which you walk out with at least the $100 you startedwith, but you could instead ask it to compute the average dollaramount that you end up with each night, by writing something like

score <- function() {  n <- 1e4  x <- 0  for(i in 1:n)    x <- x + oneNight()  x/n}

If you copy and paste that in and run 'print(score())' again, R willprint a number around 89, meaning that on average you take home $89each night. In fact, in this specific example, you actually takehome either at least $200 (in 37% of the cases) or something close tozero (in 63% of the cases), which simply happen to average to $89:in no case do you ever take home an intermediate value like $89.

Notice that $89 is less than your initial $100 balance. Thisis bad: it means that on average, you lose $11 each night. The morenights you play this game, the more you lose. Yes, on any given night,you might win, and temporarily reverse the trend, but if you play manynights, you will find your money draining away, slowly and not quitesteadily, but inescapably.

If you like, you can even see a histogram or density plot showing thevariety of outcomes:

score <- function() {  n <- 1e4  x <- c()  for(i in 1:n)    x <- c(x,oneNight())  plot(density(x))  mean(x)}print(score())

Here's the result:

You see a large peak near zero (you never really go negative, that'sjust an artifact of the smoothing process inherent in drawing thecurve), and a smaller peak at and above $200. If you win the first twobets, you walk away with $225, but other combinations of wins andlosses can lead to a variety of other winning outcomes between $200and $300.

I've been saying you will get an answer "close" to $89, because eachtime you run the program, you will get different random numbers, andso get a slightly different final answer. That's why we simulate10,000 different nights: it helps average out the noise, so that youwind up with a pretty consistent analysis, regardless of the specificroll of the dice. If you want to always get the same answer each time,put 'set.seed(123)' at the start of the code instead.

Mathematicians call this sort of situation a "random walk", becauseyour balance staggers randomly up and down over time, and it has"absorbing barriers" at $2 and $200, because once you reach (or pass)those values, you stop. Here is a picture of one particular night,showing your balance over time:

In this example, you won the first bet, but then lost the nexttwo. Then you won again, but then you lost 5 times in a row, whichforced you to stop.

So far, so good (or bad). Whether you like the odds reflected in these pictures or not, they are the results of betting half your cash each time, in a double-or-nothing game with a 48% chance of winning, given that you stop if you double your initial cash. But the real question is, "compared to what?" We need to try some alternative strategies to see if they are better or worse.

We assume you cannot change 'w' and 's', because those arefixed characteristics of the game you are playing. In reality, youcould go look for a different, more favorable game, but 48%double-or-nothing is about as favorable as typical casino games get,actually.

So what can you change? You can change 'f', or you can modify the'nextBet' function to do something else, such as bet a fixed dollaramount each time, rather than a fixed percentage. This is easy enough:type in

f <- 25nextBet <- function(m) {  if(m >= 200) 0  else f}

and now 'f' is the fixed dollar amount of each bet, in this case $25each time.

So, try some experiments. Change 'f' to reflect different fractions ordifferent fixed size bets, and see what happens. Draw the densitycurves to see the whole story, or just pick the strategy with thehighest score. Let me know in the comment section if you find astrategy you think is really good - but be warned, ultimately, acasino exists to take your money, so stick with computer simulationsand stay out of actual casinos. One can in fact prove, mathematically,that in this sort of game there is NO "winning" strategy, meaning onethat returns on average more than your original $100. You can keepyour original $100 by not going to the casino at all, but the moreoften you bet, the more likely you are to lose.

To demonstrate that last remark, here are the results if you bet yourfull balance in one big bet: you get a 48% chance of walking away with$200, making this strategy "better" (by my scoring definition) thanthe first one we looked at, since that only gave you a 37% chance ofwinning. This raises your average payout to $96, still less than the$100 you started with (as I said, this is unavoidable), but betterthan the $89. Of course, you don't have as much "fun", since theevening is over after just one bet, either way. The distribution ofoutcomes is very sharply peaked, at zero and at $200, since these arethe only two possible outcomes.

Conversely, if you decide to make the evening last by making smallerbets, you wind up hurting your chances of winning: the more often youbet, the more likely it is that the casino takes your money, becausethe odds are in its favor. If we set 'f <- 0.1' in our originalcode, so that you bet only 10% of your balance each time, you win onlyabout 26% of nights, and your average balance is $61. The distribution ofoutcomes is also more skewed: more probability of losing everything,less of reaching, let alone exceeding, $200, as shown in the image atthe very beginning of this post.

Similarly, if we make a fixed size small bet, say $10 each time, weget a 30% chance of winning, and a $62 payout. Again, the results areworse financially than just betting your whole $100 in one shot,although they might provide more "entertainment value" since you getto keep playing longer.

Now it's your turn. Think up some new strategies you would like tocompare, code them up and see what you can discover! What happens,for instance, if you limit yourself to 20 bets rather than continuingto play indefinitely until you reach zero or $200? (Hint: modify the'oneNight' function to count the number of bets 'n', then add '& n<= 20' in the condition of the 'while' loop.) (Warning: nostrategy, no matter how clever, will prevent you from losing money atthis game, so don't try it with real money!)

If you liked this article, you may also like Supply, Demand and Market Microstructure for a more elaborate, "agent based" simulation of economic activity, or check out the Contents page for a complete list of past topics.

Please post questions, comments and other suggestions using the box below, or email me directly at the address given by the clues at the end of the Welcome post. Remember that you can sign up for email alerts about new posts by entering your address in the widget on the sidebar. If you prefer, you can follow @ingThruMath on Twitter, where I will tweet about each new post to this blog. The Contents page has a complete list of previous articles in historical order. Now that there are starting to be a lot of articles, you may also want to use the 'Topic', 'Search' or 'Archive' widgets in the side-bar to find other articles of related interest.

I hope you enjoyed this discussion. You can click the "M"button below to email this post to a friend, or the "t" button toTweet it, or the "f" button to share it on Facebook, and so on. Seeyou next time!