Random walks

Random walks

 https://www.khanacademy.org/computing/computer-programming/programming-natural-simulations/programming-randomness/a/random-walks
벡터,물리적 움직임의 특성에 들어가기 앞서 어떤것(오브젝트)가 스크린주위에서 단순히 움직이는것이 무엇을 의미하는지를 생각해 보자. 그리고 우리가잘 알고 있고 가장 간단한 움직임의 시뮬레이션인 랜덤워크를 시작해보자
니가 평균대(balance beam)의 중앙에 서있다 상상해 보라, 매 10초마다 너는 동전을 뒤집는다
앞(head) 면 앞으로 한발, 뒤(tail)이면 뒤로 한발 이게 랜덤워크이다.
경로는 랜덤한 스텝의 연속으로 결정된다. 평균대 그리고 마루에서 행진해보자
그리고 너는 2가지 차원으로 랜덤워크를 시행할 수 있다  같은 동전을 2번 던저… 아래 결과 같이

 

Flip 1 Flip 2 Result
Heads Heads Step forward.
Heads Tails Step right.
Tails Heads Step left.
Tails Tails Step backward.

그렇다 이건 특별히 세련된 알고리즘이 아닌것 처럼 보임다. 그럼에도 불구하고, 랜덤 워크는 가스의 분자 운동에서 카지도의 겜블러의 일상 행동 까지와 같은 실상에서 발생하는 현상의 모형이 이 될 수 있다.
as for us,   머리속에 3가지 목표를 가지고 랜덤워크를 연구하여 이 주제를 시작한다..

The Random Walker Object

자바스크립트에서 하나의 오브젝트를 속성과 그것에 속해있는 기능 을 가진다. 이 예제를 보면
우리는 스크린 어디에 위치 할지 데이터를 계속 추적하고 스텝을 밝거나 가지 스스로를 그리는 등의 갑작스러운 행동을 실행할수 있는 능력을 가지도록 설계된  Walker 를 볼 수 있다.

Walkers 의 인스턴스들이 생상되기 위해서는 Walkers가 정의되어야 한다. 오브젝트는 쿠키 커터 라고 한다면 각각의 새로운 Walkers인스턴스는 쿠키가 된다.

Walkers오트텍트 형태를 정의하면서 시작해보다. Walkers는  x좌표, y좌표 를 나타내섯 숫자 데이터 2가지만 필요하다.  이것을  function 생성자 안에 화면 가운데 놓이 도록 설정한다.

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

그리고 그것의 x,y 의위치 확인뿐아니라 Walkers객체 가 그것을 부를수 있도록 하는 메소드를 가질 것이다. 첫째는 까만점으로 자신의 위치를 나타내는 객체를 허락하는 메소드이다. 자바스크립트에서는 객체에 prototype를 붙여서 메소드를 추가 하는것을 기억하라

Walker.prototype.display = function() {

    stroke(0, 0, 0);
    point(this.x, this.y);
};

두번째 메소드는 Walker 객체가 스텝을 하도록 지시하는 메소드 이다 
4가지의 가능성이 있다 좌 우 앞 뒤 그럼 어떻게 이 4가지 경우중에서 선택하지? 
먼저 2코인을 던지는것으로 시작할 수 있다. 그러나 ProcessingJS에서는 random()을 사용한다 

Walker.prototype.walk = function() {

    var choice = floor(random(4));
};

위에 코드는 0에서 4중 부동 소수점(floating point number ) 수 하나를 무작위로 선택하고 그걸을 floor()를 이용해서 정수(whole number)로 바꾼다. 결과는 0,1,2,3중 하나, 기술적으로 가장 높은 수로 4는 될수 없다. 3.999999999까지.. floor()가 같거나 이하의 정수를 리턴하기 떄문에 최대값은 3이 됨...그래서 4가지 경우를 선택해서 좌우위아래를 스텝을 밟아주면 됨.
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--;
    } 
};

이제는 class에 대해 이야기 해본다. 이제는 실제 Walker 객체 를 만들어 볼 때이다 
싱글 랜덤 워크를 생성하려고 가정한다면 Walker타입의 글로벌 변수를 선언하고 초기화 한다. 어떻게? new 연산자(operator)로 함수생성자를 불러냄으로써... 

 

var w = new Walker();

그리고 애를 뭔가 하게 만들어야지? draw()함수를 정의한다. 어떻게? walker한테 스텝을 밟도록 지시하고 그렇게 호출되었을때 자신을 그릴수 있도록 한다..
var draw = function() {
    w.walk();
    w.display();
};

background()를 안불렀기 때문에 우리는 화면에서 랜럼워크의 궤적을 볼 수가 있다...

 

Improving the Random Walker

한단계 더 발전시켜…   윈도우의 픽셀은 8개 이웃과 그대로 같은 장소이 있는 총 9개의 경우의 수가 있다

There are a couple improvements we could make to the random walker. For one, this walker’s step choices are limited to four options—up, down, left, and right. But any given pixel in the window has eight possible neighbors, and a ninth possibility is to stay in the same place.

Nature of Code ImageFigure I.1

위와 같은 방법보다 더 효율적은 방법으로 코드를 바꿔 보자면 x축에서 -1 0 1 중 하나 선택하고 y축에서 -1,0,1 선택하는  간단한 방법도 있음

To implement a Walker object that can step to any neighboring pixel (or stay put), we could pick a number between 0 and 8 (nine possible choices). However, a more efficient way to write the code would be to simply pick from three possible steps along the x-axis (-1, 0, or 1) and three possible steps along the y-axis.

Walker.prototype.walk = function() {
  var stepx = floor(random(3))-1;
  var stepy = floor(random(3))-1;
  this.x += stepx;
  this.y += stepy;
};

Taking this further, we could use a decimal for x and y instead and move according to an arbitrary random value between -1 and 1 – if our environment could actually display the difference between “2.2” and “2.4”:

Walker.prototype.walk = function() {
  var stepx = random(-1, 1);
  var stepy = random(-1, 1);
  this.x += stepx;
  this.y += stepy;
};

All of these variations on the “traditional” random walk have one thing in common: at any moment in time, the probability that the Walker will take a step in a given direction is equal to the probability that the Walker will take a step in any direction. In other words, if there are four possible steps, there is a 1 in 4 (or 25%) chance the Walker will take any given step. With nine possible steps, it’s a 1 in 9 (or 11.1%) chance.

Conveniently, this is how the random() function works. Its random number generator produces what is known as a “uniform” distribution of numbers. We can test this distribution with a program that counts each time a random number is picked and graphs it as the height of a rectangle:

의문점

var stepx = floor(random(3))-1; 에서 -1은 뭐지?
random(-1, 1)만해도 되나? 1픽셀씩 움직이니까 그 아래 숫자는 의미가 없다는 뜻인가? 


https://www.khanacademy.org/computing/computer-programming/programming-natural-simulations/programming-randomness/a/random-walks

You may also like...