martes, 22 de noviembre de 2016

A simple Monte Carlo Methods: Compute Pi

very interesting links

http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/07/compute-pi.html
http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/01/alg.html
http://www.dreamincode.net/forums/topic/30265-calculate-pi-using-random-numbers/

http://www.wikihow.com/Calculate-Pi-by-Throwing-Frozen-Hot-Dogs

http://mathworld.wolfram.com/MandelbrotSet.html
http://www.wikihow.com/Plot-the-Mandelbrot-Set-By-Hand
http://www.wikihow.com/Calculate-Pi-by-Throwing-Frozen-Hot-Dogs
http://arachnoid.com/mandelbrot_set/
http://ccl.northwestern.edu/netlogo/models/Mandelbrot

A simple Monte Carlo Methods: Compute Pi





  • Pseudo random number generator
    • Terminology:
        • Pseudo random number generator = a device (method) that generate random numbers taken from some distribution of values
    • Commonly used distribution of values:
        • Uniform [a,b] distribution
            • Every value between a and b is generated with equal probability (likelihood)


        • (Standard) Normal distribution
            • The value are generated with the following distribution of probability (likelihood)



  • The uniform [0,1) pseudo random number generator in the java.lang.Math class
    • The method random() returns a uniform [0,1) pseudo random numberThat means it can return any values between 0 and 1, including 0. but not including 1.


    • Example: print 10 random numbers (between [0, 1))

           public class Random1
           {
              public static void main(String[] args)
              {
             
             for ( int i = 0 ; i < 10; i++ )
             {
                System.out.println( Math.random() );    // Print a random number     
             }
              }
           }
        


    • Example Program: (Demo above code)                                                 
      How to run the program:

        • Right click on link and save in a scratch directory
        • To compile:   javac Random1.java
        • To run:          java Random1









  • Monte Carlo experiments
    • Monte Carlo experiments are experiments with a random outcome with a certain probability of successExample: Monte Carlo experiment

        • Die roll with outcome = 6
        • The probability of this experiment = 1/6


    • If the probability of success of the Monte Carlo experiment is difficult to compute, we can obtain an approximation using the following procedure:
        • Performing the Monte Carlo experiment for many many many times and observe the outcomes.
        • The probability of success of the Monte Carlo experiment can be approximated by:

              # times that the outcome was succesful
             -----------------------------------------        
             # times that the experiment was performed
            


    • Monte Carlo Method:
        • Monte Carlo Method = a computer simulation that performs Monto Carlo experiments aimed to compute the above probability

    • We will illustrate the Monto Carlo Method with a simple experiment to find Pi









  • Monte Carlo experiment to find an estimate for Pi
    • Problem:
        • Assume we have no knowledge of the value of π (= 3.1415926535...)
          I.e., you cannot your calculator or any other information source.
        • Find an estimate for π
      We will now design a Monte Carlo experiment that can be used to find an estimate for π.



    • Consider the following funny looking dart board:
        Facts:

          • The dimension of the dart board is 1 x 1.
          • quarter circle with radius r = 1 is inscribed in the board.


    • The Monte Carlo experiment:
        • You throw darts at this board blindfolded(we check only the darts that land on the board)
          When you are blindfolded, then the probability of a dart landing on any position inside the 1 x 1 quared board is identical)


        • What is the probability that a dart hits the yellow portion of the dart board ???



    • Computing the probability that a dart hits the yellow portion of the dart board:
        • Fact from the construction of the dart board:

                                                   Area of the quarter circle
               Probability [ dart hits yellow portion ] = --------------------------      
                                                    Area of the 1 x 1 square
            
                                                        = Area of the quarter circle
            
          (Because the area of the 1 x 1 square is equal to 1).
    • The area of the quarter circle can be computed as follows:

        • The area of the full circle = π × 1 2 = π
        • The area of the quarter circle = π / 4



    • Therefore:

           Probability [ dart hits yellow portion ] = Area of the quarter circle     
        
                                                    = π/4
        



  • Finding an estimate for Pi using a Monte Carlo Method
    • The above description give rise to a Monte Carlo experiment that we can use to estimate π.
    • Recall Monte Carlo experiment:
        • An experiment (= throwing darts) with a random outcome with a certain probability of success (= darts land inside the quarter cicle with probability = π/4)
      We can use a Monte Carlo Method (simulating throwing darts) to estimate this probability of success !



    • Monte Carlo Simulation (throwing darts):

           int i;          
           int nThrows = 0;        
           int nSuccess = 0;        
         
           /* ==============================
              Throw a large number of darts
              ============================== */          
           for (i = 0; i < aLargeNumber; i++)      
           {        
              "Throw a dart";       
              nThrows++;         
                      
              if ( "dart lands inside quarter circle" )   
            nSuccess++;        
           }          
         
           /* =================================================================
              Estimate the probability of a dart landing inside quarter circle
              ================================================================== */
           System.out.println("Pi/4 = " + (double)nSuccess/(double)nThrows );
        



    • Simulating a dart throw:
        • computer program can never throw a real dart
        • simulation will only consider the result of a dart throw
        • Result of a dart throw:
            • The dart lands in some coordinate (xy) where x and x are uniform [0..1) distributed(I.e., any point inside the 1 x 1 square will be equally likely to be "hit")


        • Simulating a dart throw:
            • x = Math.random()
            • y = Math.random()         



    • Checking whether a dart landed the inside the quarter cicle:

        • A point (x,y) inside the quarter circle will satisfy the following inequality:



                x2 + y2 ≤ 12    (Equation of a circle)     
            




    • Java program of the Monte Carlo Simulation:

           public class ComputePi1
           {
              public static void main(String[] args)
              {
             int i;                                                               
             int nThrows = 0;                                             
             int nSuccess = 0;                                            
                    
             double x, y;                                                 
                    
             for (i = 0; i < 1000000 ; i++)                         
             {                                                            
                x = Math.random();      // Throw a dart                   
                y = Math.random();                                                
                    
                nThrows++;                                                        
                    
                if ( x*x + y*y <= 1 )             
                   nSuccess++;                                               
             }                                                            
                    
             System.out.println("Pi/4 = " + (double)nSuccess/(double)nThrows );
             System.out.println("Pi = " + 4*(double)nSuccess/(double)nThrows );
              }
           }
        
      Output:


           Pi/4 = 0.785784                  
           Pi = 3.143136
        



    • Example Program: (Demo above code)                                                 
      How to run the program:

        • Right click on link and save in a scratch directory
        • To compile:   javac ComputePi1.java
        • To run:          java ComputePi1









  • More interesting Monte Carlo simulations
    • In the 1960's, Edward Thorp wrote and published the book "Beat the Dealer" on Black Jackclick here

    • The book presents a system of card counting and how to play Black Jack
    • Many people have written computer programs that simulate a Black Jack games (among them was me :-))
    • The simulations show that Thorpe system does work - you can win at Black jack with his system by counting cards.
    • As a result, casinos in Las Vegas impose measures to throw out people that count cards...

domingo, 20 de noviembre de 2016

5 Unexpected Downsides of High Intelligence

5 Unexpected Downsides of High Intelligence

You know that phrase, "Ignorance is bliss"? There's a reason it's stuck around all these years. Because having the upper hand in intelligence might give you an advantage in some areas, like crossword puzzle solving and quantum physics-ing, but it also might just screw up your life forever.
Note: Stephen Hawking can talk about how dangerous AI will be in the future, but we're not worried. Because, as this Cracked Classic shows, the more dangerous dangerous robotsgather, the more they'll sabotage their own well being, until all the Terminators work themselves to death while the ED-209s drown their inadequacy issues in robo-whiskey. So enjoy this article, and be less scared of robots. -Cracked
For instance, if you're smart ...
5
You're Probably a Night Owl -- And That's a Bad Thing
Getty
Recently, scientists discovered a quirky side effect to having a high IQ: You tend to stay up until later hours and get up later in the morning. That's right -- the more intelligent are also much more likely to be night owls. Which isn't such a surprise when you consider that intelligent people are infamous for burning the midnight oil to cram for tests, write papers, touch up those earnings reports, etc.

It appears to just be evolution -- the more intelligent members of a species are, in general, the first to change habits (their big brains are wired to seek out novelty). Since humans have been day-dwellers during most of their existence, it's primarily the smarties who prefer to habitually stay up until the wee hours and to do the types of tasks that are easier to accomplish when you don't have the day-dwellers hanging around and distracting you. Stuff that requires concentration, in other words.
So let the early birds keep their measly worms. The nights owls get to feast on the juicy field mice of accomplishment!
So What's the Problem?
Well, being a night owl does have some negative side effects. And by "some" we mean, "You're pretty much screwed."

For starters, studies have found that "eveningness" is associated with a high degree of emotional instability. That means you tend to be less agreeable and conscientious than the average Joe. Oh, and you don't just make others' lives miserable. Thanks to your late-night habits, likely brought on by high intelligence, you're also three times more likely to suffer symptoms of depression.
And the fun doesn't end there, geniuses! Turns out that, short of becoming a competitive asbestos eater, staying up late at night is about the worst thing you could do for your physical health. According to a number of studies, night owls are at higher risk for heart disease and suffer more arterial stiffness than those who go to bed early.
The direct cause might have less to do with the fact that you stay up than with some of the other things you're doing while your eyes get all nice and bloodshot. You see, people who tend to stay up late also tend to do other unhealthy things at night, such as overeating. Then, once they do eventually hit the hay, they experience more sleep interruptions when those pesky morning larks get up and start noisying about.
All this adds up to some nasty artery stress and whacked-out circadian rhythms, a nice recipe for a massive coronary. So be sure to thank those dumbass early risers and your high intelligence for your inevitable heart attack.
Photos.comCauses of death: Morning-type wife and a 155 IQ.
4
You're Less Likely to Pass On Your Genes

Another unfortunate stereotype of smart people is that they're socially awkward nerds who are doomed to lives of celibacy until they get out of high school hell. Unfortunately, that one turns out to be totally true.
But it's not all bad news. There's evidence that the highly educated get more enjoyment out of sex than the dumb jocks and that really, all the lovin' you need to be happy comes from having sex with just one partner per year. So even the nerdlingers among us can find one person to get along with, then have highly enjoyable loser-geek sex, eventually leading to populating the planet with loser-geek children, right?

So What's the Problem?
Smart boy, please. Those genes you're carrying aren't going any-goddamn-where. Unbeknownst to the smarties, their education levels and IQ are conspiring to keep them childless and perhaps leading them to adopt 30 cats when they're in their late 70s.
It all starts with the smart ladies. A 2008 national census reported that women who had dropped out of high school had the most children on average. And the more education women achieved, the fewer children they were likely to have, with the fewest children being born to women who had finished graduate school.

The explanation, according to the Census Bureau, is simple: Women wanted to finish school before they were saddled with nine months of fetus-carrying. Then, for smart people of both sexes, there's the career to think about, and promotions, and who has time for a needy mini-human during all that? And of course, IQ plays a direct role here, since it has also been found that women with lower IQs are less likely to know how to use birth control properly, leading to more unplanned pregnancies.

But that's just the ladies. The smart fellas must be picking up the slack somehow, right? Maybe by getting a little dumb-girl nookie on the side? Not so. Research shows that countries with high national IQs tend to have lower childbirth rates in general compared with countries that can't collectively tie their shoelaces together. That's right -- entire nations are missing the evolutionary point of fucking as their IQs rise.
Continue Reading Below
Around The Web
3
You're More Likely to Lie
Getty
The problem with being the smartest guy in the room is that you usually know you're the smartest guy in the room. For some people, that's not a big deal. They can relate to others just fine and know how to navigate around everyone else's deficiencies without being complete pricks. Others, however, know they have an intellectual edge and can't help but abuse it.
So What's the Problem?
In addition to giving you an advantage in brainpower, IQ apparently also bestows the gift of deception.

After all, in order to lie and get away with it, you also have to keep the truth in mind and manipulate it, and you might even have to cover up your lies upon further questioning. All of this involves integrating several brain processes in much the same way that you would solve a complex calculus problem. This means that the age at which you start lying, and the effectiveness with which you do it throughout your life, are controlled by how smart you are.
In one study, scientists put people in brain-imaging machines and found that the regions of the brain that light up when a person metaphorically sets his pants on fire are the same that control "executive functioning." These are high-order thinking and reasoning abilities that include working memory, which, you guessed it, is the single biggest component of your IQ.

Another study simply tracked the tendency of children to lie as they got older (that is, as that aforementioned part of their brains developed). The researchers simply placed young kids in a room with a toy Barney under a cloth and told the kids not to peek at the toy when the researchers left the room.

Of course, 9 out of 10 kids totally peeked, but the percentage of kids who lied about whether they peeked grew as the kids got older. At age 2, 25 percent of the kids lied about peeking; at age 3, half lied; and by age 4, 90 percent of the kids who peeked at the purple dinosaur refused to admit their guilt. That would also seem to imply that the 25 percent of kids who fibbed at age 2 possessed higher cognitive abilities than their peers.
In other words, if you want to know whether your kid is gifted, simply track the specific age at which he starts trying to bullshit you. Speaking of which ...
2
You're More Likely to Believe Bullshit

We're sure that at some point, someone has told you that you can't get anywhere without an education, and for the most part, they're right. And you're much more likely to pursue that education if you're starting out with a high IQ. According to renowned intelligenceologists who painstakingly measured every goddamn thing that you can associate with IQ, test scores were "the best single predictor of an individual's years of education."

Why? Well, their theory goes that smarter students do better in school (Cracked breaks new ground yet again!), which leads to more encouragement from teachers and parents, which in turn leads to more motivation to stay in school, then yadda yadda yadda, bingo-bango, master's degree in economics!
So What's the Problem?
It turns out that all this book learnin' is teaching you more than just the Pythagorean theorem -- it's also making it easier for you to believe some laughably wrong and even seriously weird stuff.

One problem is that education leads to one overall inaccurate belief: You think you're smarter than you are. Three studies have found that people who fall for investment scams are better-educated than the average person but don't seek advice because they think they're immune to making mistakes. In one study, researchers found that 94 percent of college professors think their work is superior to their peers'. These fellows fail to realize that intelligence doesn't always translate to real-world ability, and thus they tend to overestimate the quality of their work.

It seems to go back to the old saying about how the wisest man is the one who realizes he knows nothing. Or, as Michael Shermer, the author of Why People Believe Weird Things, puts it: "Smart people believe weird things because they are skilled at defending beliefs they arrived at for non-smart reasons."
That's why the more education you get, the more likely you are to believe in, say, ghosts and the supernatural. One study found that 23 percent of college freshman believed in the paranormal, compared with 31 percent of seniors and 34 percent of graduate students. Which leads us to wonder ... what the fuck are schools teaching these days?
Continue Reading Below
1
You're More Likely to Be Self-Destructive
Getty
On one hand, it seems like the smarter you are, the greater your ability to know the dangers of, say, shooting heroin. So self-destructive habits are traits of the low-class and stupid, right? Eh, not really...
The thing is, the great minds have something in common with proverbial death-prone kitties: curiosity. Researchers have finally begun to understand the link between curiosity and intelligence on the molecular level, thanks to scientists from the University of Toronto and Mount Sinai Hospital who discovered a protein in an under-explored part of the brain that controls both traits.

Makes sense. Weird shit like monkey-powered time machines can be invented only by people with enough brain smarts to make them work and enough curiosity to want to see such awesomeness in the first place.
So What's the Problem?
Extra-curious people are also extra-likely to be substance abusers.
British scientists published the results of a long-term study showing that smart people were more likely to be drunks. People who fell into the "very bright" category (IQs of 125 or greater) were not only more likely to experiment with alcohol but also were more likely to drink excessively and binge drink than their dimwitted counterparts.

And yeah, they pretty much found the same link between high intelligence and psychoactive drug use. It also turns out that intelligent people are much more likely to indulge in illicit substances such as marijuana, Ecstasy, cocaine and heroin. The smarter you are, the more likely you are to be tripping balls at any given moment.

As for why, remember when we said earlier that smart people's brains seek out novelty and thus are the first to experiment with any new habit? Well, one theory explaining the link between substance abuse and intelligence is that both alcohol and drugs are novel substances, in evolutionary terms. Humans have been consuming alcohol for only about 10,000 years, and the earliest recorded drug was only 5,000 years ago. So when something is novel, the curiouser and most intelligent among us are more likely to want to try it out.



chessplayers

    Many chessplayers live in a world of their own. The game of chess has touched off some very bizarre behavioral patterns among chessplayers. Here are some examples of the eccentrics of chess.
    Alekhine was famous for his eccentrics. He drank very heavily and was nicknamed "Ale-and-Wine." In a few tournaments he was found in a field drunk. He would urinate on the floor in other events. He married four times to women 20 to 30 years older than he.
    Nimzovich stood on his head during chess events or did exercises in the tournament room. After losing a game, he once jumped up on the table and yelled, "Why must I lose to this idiot."
    The Mexican master, Carlos Torre, was found running down Fifth Avenue in New York in the nude.
    Tartakower lost 5 games in a row and was asked why. He replied, "I had a toothache during the first game. In the second game I had a headache. In the third game it was an attack of rheumatism. In the fourth game, I wasn't feeling well. And in the fifth game? Well, must one have to win every game?"
    Steinitz had delusions of telephoning people without any phone. He thought he could emit electrical currents and move chess pieces at will. He even claimed to be in direct contact with God and occasionally beating Him at chess with pawn odds.
    Morphy imagined himself persecuted by his relatives and went into a state of seclusion. He thought his food had been poisoned or that someone was trying to kill him. He had a fetish with women's shoes.
    Rubinstein was so paranoid that if a stranger came into his room, he would run or even jump out of a window. In chess tournaments he would make a move then stand as far away as possible from the board until his next move. During World War I, he invested all his money in German War Bonds.
    Emanuel Lasker was a successful chessplayer but a failure as a farmer. He once tried to breed pigeons and enter them in poultry shows. He tried for many months and failed. The pigeons were all male.
    Blackburne hated to lose at chess so badly that he once threw an opponent out the window after losing a game.
    Capablanca refused to pose with a film star, saying, "Why should I give her publicity?"
    Henrique Mecking lost his match with Petrosian and made a formal protest. He accused Petrosian of kicking the table, shaking the chessboard, stirring the coffee too loudly, and rolling a coin on the table. He went to the referee twice to complain that Petrosian was breathing too loudly. Mecking kicked back at the table and started making noises of his own. Petrosian responded by turning his hearing aid off.
    William Russ was the leading American compiler of chess problems in the 19th Century. He adopted an 11-year old girl and proposed to her when she turned 21. When she rejected him, he shot her 4 times in the head, then shot himself twice. She survived, he did not. His chess book, published posthumously, was entitled AMERICAN CHESS NUTS.
    David Janowski was a great chessplayer and an addicted gambler. In one tournament in Monte Carlo, he gave all his money to a friend and made him promise not to return the money until after the event. However, the lure of gambling was too much and he begged his friend to return his money. His friend refused, so Janowski sued his friend.
    Bobby Fischer could have played Boris Spassky anywhere in the world for millions of dollars in their 1992 re-match. Instead, he agreed to play in Yugoslavia against US and UN sanctions. He spit on the U.S. Department of Treasury warning not to play in Yugoslavia, played anyway, and is now facing 10 years in prison and a $250,000 fine. In 1999 he gave radio interviews denying the holocaust of the Nazis and accusing the Jewish community of conspiring against him (Fischer is half Jewish). After the September 11, 2001 terrorist attack on the U.S., Fischer applauded the attacks and said America deserved it. In 2002, he made a radio interview encouraging the Icelandic government to kick out the U.S. military from Iceland. He encouraged the Icelandic government to send anthrax to the U.S. government if the U.S. failed to leave Iceland

sábado, 12 de noviembre de 2016

corrupcion en el instituto de materiales de la UNAM

Interesante articulo sobre lo que es un secreto a voces, la corrupción, negligencia, malas practicas y opacidad de los institutos de investigación de la UNAM

http://www.contralinea.com.mx/archivo-revista/index.php/2016/07/10/corrupcion-estructural-en-la-unam-caso-instituto-de-investigaciones-en-materiales/


Desaparición de recursos millonarios, falsificación de firmas y sabotaje de un proyecto científico de alcances internacionales; además de represalias contra los denunciantes, son algunas de las irregularidades ocurridas en el Instituto de Investigaciones en Materiales de la UNAM, al amparo de los rectorados de José Narro y Enrique Graue.


Hasta el momento, la transferencia de los resultados no se ha realizado. Tampoco se le pagó al desarrollador del software VisCalc-Pemex, Rolf Mertig. Además, “el cierre del laboratorio sin previo aviso que estas mismas autoridades hicieron el 29 de enero de 2016, interrumpieron las actividades del laboratorio sin dejarnos oportunidad de hacer los procedimientos para asegurar el equipo, para su conservación”, apuntó uno de los alumnos que a la vez señaló que el trato ha sido denigrante por parte de la directora y de la administración del IIM:
“Sobran y colman los ejemplos de malos tratos, mismos que únicamente socavan la propia autoridad de la directora, así como de su administrador y su representación de nuestra máxima casa de estudios.”
A principios de marzo, ya con la fecha de entrega vencida, Efraín Luna –inmune a la sanción impuesta por la Contraloría– les comunicó a los estudiantes colaboradores que por fin podrían cobrar el mes de enero, sólo había una condición: que entraran al laboratorio abandonado y “limpiaran” los equipos.
El malestar de los alumnos coincidió en señalar a Efraín Díaz no sólo de maltrato, sino de extorsión e intento de adjudicarles el daño del laboratorio.
Ante la insistencia del Conacyt, la UNAM se dio cuenta de la importancia de entregar oficialmente el proyecto.
El físico Geffroy Aguilar considera que el hecho de “que una institución de la Universidad no les pague ni siquiera una beca a los estudiantes que participan en los proyectos es vergonzoso e indignante. Cuando a un estudiante no se le paga, y tiene que irse a trabajar y deja tirados sus cursos y sus grados, quiere decir que no les importa que se gradúen o no. Eso no sólo va en detrimento del estudiante o de una investigación, va en detrimento de la Universidad y del país”.
El 13 de mayo de 2016, William Lee se comunicó personalmente con el Conacyt para pedirle su intervención para que Quiñones impartiera el curso de capacitación a los empleados de Pemex y que el Conacyt cubriera los gastos de todo (oficio COIC/CSGC/1585/16). Incluso aseguró que era necesario cubrir de una vez el adeudo con el desarrollador del software.
El 22 de junio Néstor Díaz y Enrique Puchet contestaron a nombre del Fondo con una negativa: “Se tiene que comprobar la presencia del reómetro capilar, fabricado en Alemania, en las instalaciones de la UNAM, funcionando o, en su defecto, el reembolso al Fondo del costo del equipo” (oficio ST/FH/434/2016).
Entre la presión del Colegio del Personal Académico del IIM, que formalmente pidió el 25 de mayo a la Junta de Gobierno y al rector la destitución de Ana María Martínez; las preocupaciones expresadas por Schulumberger y el Instituto Fraunhofer, que incluso analiza iniciar un proceso contra la Universidad, y la insistencia del Conacyt de que se resuelva el conflicto, la Coordinación de Investigación Científica ha tomado el caso directamente, haciendo a un lado a la dirección del IIM, pues se podría dar el caso de que los resultados de la investigación se entreguen a Pemex… dejando fuera a la UNAM.

lunes, 12 de septiembre de 2016

Perspectivas educativas


Esta caricatura es muy cierta, la realidad es que los que estudiamos maestria y doctorado enfrentamos desempleo al salir de la graduacion, ya con nuestro titulo en la mano y la cedula profesional; las empresas no reconocen estos logros; las empresas te ven como un trabajador sobrecalificado, o un bicho raro (eres FISICO matematico! como cress!!), y te esperan salarios de miedo en las universidades publicas como profesor de materia recuerdo que ganaba unos 2500 pesos AL MES!!!, a menos que seas familiar de una vaca sagrada, como varios companieros que tuve en el doctorado por ejemplo: mariano chernikov, colabita, y varios que ahorita no recuerdo su nombre, las becas estaban aseguradas por sus compadres directivos de los institutos, su cubiculo estaba asegurado, aunque realmente no hubieran contribuido con sus articulos publicados en revistas "internacionales" que se vuelven uno mas del monton...