by jane kim(김해인) 2015.10.11에 작성: Vector개념을 배우고 이를 코드로 작성해 보았습니다..

코드 실행: https://www.khanacademy.org/computer-programming/pvector-instance/6479887750266880


/**

Try to catch the ball! It's harder when you move, but easy when you stay..... :)


Line 37: The reason why I used constrain() is because sometimes(or mostly) when you move your mouse in further directions, the ball can get off the canvas. Making the user a bit fustrated.

So, I just used constrain() to command the code where the ball can go without further ado.(it can only move inside the canvas!)

*/


background(97, 237, 255);


//I'm puting this in a function just in case somebody tweaks this code and gets an error. (Nobody wants that to happen!)

var ball = function(x, y) {

    translate(x, y);

    noStroke();

    fill(255, 0, 0);

    ellipse(0, 0, 30, 30);

    fill(255, 255, 255);

    arc(0, 0, 30, 30, 0, 180);

    fill(0, 0, 0);

    ellipse(0, 0, 5, 5);

};


mouseMoved = function() {

    background(97, 237, 255);

    

    //Creating two new PVectors, mouse and center.

    /* The mouse is a vector showing us where the mouse is, and the center is just the center of the canvas.(In vector scale!) */

    var mouse = new PVector(mouseX, mouseY);

    var center = new PVector(width/2, height/2);

    

    /* The mouse.sub(center) is in order to let the ball to fallow the mouse. Without it, it will go away twice from the position the mouse is currently on.

NOTE: mouse.mult(3) is to make distances from the mouse and the ball 3 times further.*/

    mouse.sub(center);

    mouse.mult(3);

    

    //Since translate() is not with either pushMatrix() or popMatrix(), we have to reset the code by using resetMatrix().

    resetMatrix();

    translate(width/2, height/2);

    ball(constrain(mouse.x, -185, 185), constrain(mouse.y, -185, 185));

};


/**

Note: This is just a practice program for my vector skills, not for khantober!

*/

by jane kim

Let's say we want to make that program that generates a world of monkeys. Your program could generate a thousand Monkey objects, each with a height value between 200 and 300 (as this is a world of monkeys that have heights between 200 and 300 pixels).

var randomHeight = random(200, 300);

Does this accurately depict the heights of real-world beings? Think of a crowded sidewalk in New York City. Pick any person off the street and it may appear that their height is random. Nevertheless, it’s not the kind of random that random() produces. People’s heights are not uniformly distributed; there are a great deal more people of average height than there are very tall or very short ones. To simulate nature, we may want it to be more likely that our monkeys are of average height (250 pixels), yet still allow them to be, on occasion, very short or very tall.

       표준편차의 이해: http://bcho.tistory.com/972

     

A distribution of values that cluster around an average (referred to as the “mean”) is known as a “normal” distribution. It is also called the Gaussian distribution (named for mathematician Carl Friedrich Gauss) or, if you are French, the Laplacian distribution (named for Pierre-Simon Laplace). Both mathematicians were working concurrently in the early nineteenth century on defining such a distribution.

When you graph the distribution, you get something that looks like the following, informally known as a bell curve:

Graph of a standard bell curveA standard bell curve

The curve is generated by a mathematical function that defines the probability of any given value occurring as a function of the mean (often written as μ, the Greek letter mu) and standard deviation (σ, the Greek letter sigma).

The mean is pretty easy to understand. In the case of our height values between 200 and 300, you probably have an intuitive sense of the mean (i.e. average) as 250. However, what if I were to say that the standard deviation is 3 or 15? What does this mean for the numbers? Looking at graphs can give us a hint. The graph above shows us the distribution with a very low standard deviation, where the majority of the values cluster closely around the mean. The graph below shows us a higher standard deviation, where the values are more evenly spread out from the average:

Graph of a bell curve with a higher standard deviationA bell curve with a higher standard deviation

Not familiar with the concept of "standard deviation"? Don't worry! You can studyVariance and standard deviation separately on Khan Academy before continuing.

The numbers work out as follows: Given a population, 68% of the members of that population will have values in the range of one standard deviation from the mean, 98% within two standard deviations, and 99.7% within three standard deviations. Given a standard deviation of 5 pixels, only 0.3% of the monkey heights will be less than 235 pixels (three standard deviations below the mean of 250) or greater than 265 pixels (three standard deviations above the mean of 250).


Calculating Mean and Standard Deviation

Consider a class of ten students who receive the following scores (out of 100) on a test:

85, 82, 88, 86, 85, 93, 98, 40, 73, 83

The mean is the average: 81.3

The standard deviation is calculated as the square root of the average of the squares of deviations around the mean. In other words, take the difference from the mean for each person and square it (variance). Calculate the average of all these values and take the square root as the standard deviation.

ScoreDifference from MeanVariance
8585 - 81.3 = 3.7(3.7)^2 = 13.69
8282 - 81.3 = 0.7(0.7)^2 = 0.49
8888 - 81.3 = 6.7(6.7)^2 = 44.89
etc.... ... 
 Average Variance:228.81

The standard deviation is the square root of the average variance: 15.13

Want to understand standard deviation better? You can study Variance and standard deviation in more depth here on Khan Academy.


Luckily for us, to use a normal distribution of random numbers in a program here, we don't have to do any of these calculations ourselves. Instead, we can make use of the Randomobject provided by ProcessingJS.

To use Random, we must first instantiate a new Random object, passing in 1 as the parameter. We call that variable "generator" because what we've created can be basically thought of as a random number generator.

var generator = new Random(1);

If we want to produce a random number with a normal (or Gaussian) distribution each time we run through draw(), it’s as easy as calling the function nextGaussian().

var num = generator.nextGaussian();
println(num);

So, now, what are we supposed to do with this value? What if we wanted to use it, for example, to assign the x-position of a shape we draw on screen?

The nextGaussian() function returns a normal distribution of random numbers with the following parameters: a mean of zero and a standard deviation of one. Let’s say we want a mean of 200 (the center horizontal pixel in a window of width 400) and a standard deviation of 60 pixels. We can adjust the value to our parameters by multiplying it by the standard deviation and adding the mean.

var standardDeviation = 60;
var mean = 200;
var x = standardDeviation * num + mean;

Now, we can create our program that draws semi-transparent circles according to a normal distribution. The darkest spot will be near the center, where most of the values cluster, but every so often circles are drawn farther to the right or left of the center.


// Adapted from Dan Shiffman, natureofcode.com


var generator = new Random(1);


<코드>

var draw = function() {

    // The nextGaussian() function returns a normal distribution of random numbers with the following parameters: a mean of zero and a standard deviation of one

    var num = generator.nextGaussian();

    var standardDeviation = 60;

    var mean = 200;

    

    // Multiply by the standard deviation and add the mean.

    var x = standardDeviation * num + mean;

    

    noStroke();

    fill(214, 159, 214, 10);

    ellipse(x, 200, 16, 16);

};


    <출력>



<코드>

var generator = new Random(1);

var standardDeviation = 2;

var mean = 0;


var Walker = function() {

    this.x = width/2;

    this.y = height/2;

};


Walker.prototype.display = function() {

    strokeWeight(3);

    stroke(0, 0, 0);

    point(this.x, this.y);

};

// Randomly move up, down, left, right, or stay in one place

Walker.prototype.walk = function() {

    var xStepSize = standardDeviation * generator.nextGaussian() + mean;

    var yStepSize = standardDeviation * generator.nextGaussian() + mean;

    this.x += xStepSize;

    this.y += yStepSize;

};


var w = new Walker();


var draw = function() {

    w.walk();

    w.display();

};

<출력>



      

2# 잘못된 코드

var generator = new Random(1);

var standardDeviation = 2;

var mean = 0;

var num = generator.nextGaussian();


var Walker = function() {

    this.x = width/2;

    this.y = height/2;

};


Walker.prototype.display = function() {

    strokeWeight(3);

    stroke(0, 0, 0);

    point(this.x, this.y);

};


// Randomly move up, down, left, right, or stay in one place

Walker.prototype.walk = function() {


    var xStepSize = standardDeviation*num + mean;

    var yStepSize = standardDeviation*num + mean;

  

    this.x += xStepSize;

    this.y += yStepSize;

};


var w = new Walker();


var draw = function() {

    w.walk();

    w.display();

};

<출력>


3#절충형

var generator = new Random(1);

var standardDeviation = 2;

var mean = 0;



var Walker = function() {

    this.x = width/2;

    this.y = height/2;

};


Walker.prototype.display = function() {

    strokeWeight(3);

    stroke(0, 0, 0);

    point(this.x, this.y);

};


// Randomly move up, down, left, right, or stay in one place

Walker.prototype.walk = function() {

    var num = generator.nextGaussian();

    var xStepSize = standardDeviation * num + mean;

    var yStepSize = standardDeviation * generator.nextGaussian() + mean;

  

    this.x += xStepSize;

    this.y += yStepSize;

};


var w = new Walker();


var draw = function() {

    w.walk();

    w.display();

};


<출력>


<^^>





<< 칸아카데미의 Advenced JS를 학습한 내용입니다. 칸선생님 감사합니다. by 해인>>


     probability & non-uniform distributions


Remember when you first started programming here? Perhaps you wanted to draw a lot of circles on the screen. So you said to yourself: “Oh, I know. I’ll draw all these circles at random locations, with random sizes and random colors.” In a computer graphics system, it’s often easiest to seed a system with randomness. In these lessons, however, we’re looking to build systems modeled on what we see in nature. Defaulting to randomness is not a particularly thoughtful solution to a design problem—particularly the kind of problem that involves creating an organic or natural-looking simulation.

With a few tricks, we can change the way we use random() to produce “non-uniform” distributions of random numbers. This will come in handy throughout this course as we look at a number of different scenarios. When we examine genetic algorithms, for example, we’ll need a methodology for performing “selection”—which members of our population should be selected to pass their DNA to the next generation? Remember the concept of survival of the fittest? Let’s say we have a population of monkeys evolving. Not every monkey will have an equal chance of reproducing. To simulate Darwinian evolution, we can’t simply pick two random monkeys to be parents. We need the more “fit” ones to be more likely to be chosen. We need to define the “probability of the fittest.” For example, a particularly fast and strong monkey might have a 90% chance of procreating, while a weaker one has only a 10% chance.

Let’s pause here and take a look at probability’s basic principles. First we’ll examine single event probability, i.e. the likelihood that a given event will occur.

If you have a system with a certain number of possible outcomes, the probability of the occurrence of a given event equals the number of outcomes that qualify as that event divided by the total number of all possible outcomes. A coin toss is a simple example—it has only two possible outcomes, heads or tails. There is only one way to flip heads. The probability that the coin will turn up heads, therefore, is one divided by two: 1/2 or 50%.

Take a deck of fifty-two cards. The probability of drawing an ace from that deck is:

number of aces / number of cards = 4 / 52 = 0.077 = ~ 8%

The probability of drawing a diamond is:

number of diamonds / number of cards = 13 / 52 = 0.25 = 25%

We can also calculate the probability of multiple events occurring in sequence. To do this, we simply multiply the individual probabilities of each event.

The probability of a coin turning up heads three times in a row is:

(1/2) * (1/2) * (1/2) = 1/8 (or 0.125)

…meaning that a coin will turn up heads three times in a row one out of eight times (each “time” being three tosses).

Want to review probability before continuing? Study compound events and dependent probability.

There are a couple of ways in which we can use the random() function with probability in code. One technique is to fill an array with a selection of numbers—some of which are repeated—then choose random numbers from that array and generate events based on those choices.


<코드>

var stuff = [];


// We store 1 and 3 in the array twice, making them more likely to be picked.

stuff[0] = 1;

stuff[1] = 1;

stuff[2] = 2;

stuff[3] = 3;

stuff[4] = 3;


// Picking a random element from an array

var index = floor(random(stuff.length));

println(stuff[index]);


//출력 3


2#

Running this code will produce a 40% chance of printing the value 1, a 20% chance of printing 2, and a 40% chance of printing 3.

We can also ask for a random number (let’s make it simple and just consider random decimal values between 0 and 1) and allow an event to occur only if our random number is within a certain range. Check out the example below, and keep clicking restart until the randomly picked number is finally less than the threshold:


<코드>
// Adapted from Dan Shiffman, natureofcode.com

var prob = 0.10;
var r = random(1);
 
// If our random number is less than 0.1, do something
if (r < prob) {
    println("Doing something!");
} else {
    println("Waiting...");
}         

// 출력 Waiting...


3#

This method can also be applied to multiple outcomes. Let’s say that Outcome A has a 60% chance of happening, Outcome B, a 10% chance, and Outcome C, a 30% chance. We implement this in code by picking a random number and seeing into what range it falls.

  • between 0.00 and 0.60 (60%) –> Outcome A

  • between 0.60 and 0.70 (10%) –> Outcome B

  • between 0.70 and 1.00 (30%) –> Outcome C

Click the restart button to see how often you get different outcomes:


<코드>

// Adapted from Dan Shiffman, natureofcode.com


var num = random(1);

 

// If random number is less than 0.6

if (num < 0.6) {

  println("Outcome A");

// Between 0.6 and 0.7

} else if (num < 0.7) {

  println("Outcome B");

// Greater than 0.7

} else {

  println("Outcome C");

}


4#

We could use the above methodology to create a random walker that tends to move to the right. Here is an example of a Walker with the following probabilities:

  • chance of moving up: 20%

  • chance of moving down: 20%

  • chance of moving left: 20%

  • chance of moving right: 40%

<코드>

// Adapted from Dan Shiffman, natureofcode.com


var num = random(1);

 

// If random number is less than 0.6

if (num < 0.6) {

  println("Outcome A");

// Between 0.6 and 0.7

} else if (num < 0.7) {

  println("Outcome B");

// Greater than 0.7

} else {

  println("Outcome C");

}



Challenge: Make it walk up



Currently, our walker tends to walk to the right. Change the logic so that it has a 10% chance of walking right, 10% chance of walking left, 60% chance of walking up, and 20% chance of walking down.


var Walker = function() {

    this.x = width/2;

    this.y = height/2;

};


Walker.prototype.display = function() {

    stroke(0, 0, 0);

    point(this.x, this.y);

};


// Randomly move up, down, left, right, or stay in one place

Walker.prototype.walk = function() {

    var r = random(1);

     

    if (r < 0.1) {

      this.x++;

    } else if (r < 0.2) {

      this.x--;

    } else if (r < 0.4) {

      this.y++;

    } else {

      this.y--;

    }

};



var w = new Walker();


var draw = function() {

    w.walk();

    w.display();

};


<출력>

<< 칸아카데미의 Advenced JS를 학습한 내용입니다. 칸선생님 감사합니다. by 해인>>

The Random Walker Object

Let's review a bit of object-oriented programming (OOP) first by building a Walker object. This will be only a cursory review. If you have never worked with OOP before, you should go through the section on Object-Oriented JavaScript.

An object in JavaScript is a data type that has both properties and functionality attached to it, via its prototype. We are looking to design a Walker object that both keeps track of its data (where it exists on the screen) and has the capability to perform certain actions (such as draw itself or take a step).

In order to create instances of Walkers, we need to define a Walker object. We'll use that object as the cookie cutter, and each new Walker instance are the cookies.

Let's begin by defining the Walker object type. The Walker only needs two pieces of data—a number for its x-location and one for its y-location. We'll set those in its constructor function, setting them to the center of the canvas.

var Walker = function() {
    this.x = width/2;
    this.y = height/2;
};

In addition to keeping track of its x and y, our Walker object will also have methods that we can call on it. The first will be a method that allows the object to display itself as a black dot. Remember that we add methods to an object in JavaScript by attaching them to the object's prototype.

Walker.prototype.display = function() {
    stroke(0, 0, 0);
    point(this.x, this.y);
};

The second method directs the Walker object to take a step. Now, this is where things get a bit more interesting. Remember that floor on which we were taking random steps? Well, now we can use our canvas in that same capacity. There are four possible steps. A step to the right can be simulated by incrementing x (x++); to the left by decrementing x (x--); forward by going down a pixel (y++); and backward by going up a pixel (y--). How do we pick from these four choices? Earlier we stated that we could flip two coins. In ProcessingJS, however, when we want to randomly choose from a list of options, we can pick a random number using random().

Walker.prototype.walk = function() {
    var choice = floor(random(4));
};

The above line of code picks a random floating point number between 0 and 4 and converts it to a whole number by using floor(), with a result of 0, 1, 2, or 3. Technically speaking, the highest number will never be 4.0, but rather 3.999999999 (with as many 9s as there are decimal places); since floor() returns the closest whole number that is lesser or equal, the highest result we can get is 3. Next, we take the appropriate step (left, right, up, or down) depending on which random number was picked.

Walker.prototype.walk = function() {
    var choice = floor(random(4));
    if (choice === 0) {
        this.x++;
    } else if (choice === 1) {
        this.x--;
    } else if (choice === 2) {
        this.y++;
    } else {
        this.y--;
    } 
};

Now that we've written the class, it's time to make an actual Walker object in our program. Assuming we are looking to model a single random walk, we declare and initialize one global variable of type Walker, by calling the constructor function with the new operator.

var w = new Walker();

Now, to make the walker actually do something, we define the draw() function, and tell the walker to take a step and draw itself each time that's called:


var draw = function() {
    w.walk();
    w.display();
};

Since we don't call background() in the draw function, we can see the trail of the random walk on our canvas:


<코드>

var Walker = function() {

    this.x = width / 2;

    this.y = height / 2;

};

Walker.prototype.display = function() {

    stroke(0, 34, 255);

    point(this.x, this.y);

};

Walker.prototype.walk = function() {

    var num = floor(random(4));

    if (num === 0) {

        this.x++;

    } else if (num === 1) {

        this.x--;

    } else if (num === 2) {

        this.y++;

    } else {

        this.y--;

    }

};

var guy = new Walker();

draw = function() {

    guy.display();

    guy.walk();

};



+ Recent posts