(각 op가 뽑힐 확률은 지정해 둔다.) selection을 (충분히 많이) 무한 번 반복하면 각 op가 가지는 확률을 알 수 있다.
tree 1과 tree 2를 교배시켜 새로운 tree 3을 생성할 때, 각 tree 1과 tree 2의 요소(node)가 변이(mutation)을 일으킬 수 있다.
mutation
tree의 각 node에서 mutation이 일어날 확률을(여부를) 계산(선택)한다. 즉, 각 node마다 mutation probability를 가진다. (그림)
cross-over
(그림)
(1/2)*(1/2) = 1/4 그러나 (유전자 쌍의 동일한 위치에서 일어나는) cross-over 때문에 매번 다른 유전자를 지닌 자식이 나온다. => "phenotype" 대응되는 node끼리 교배 -> 우열 등의 규칙은 임의로 결정
(그림)
tree 하나를 염색체 하나로 보고 유전 법칙을 적용하자. 염색체가 (이중나선 DNA)쌍으로 존재하듯, 염색체 한 쌍을 보유하는 개체 하나 당 tree 2개로 구성되어 있다고 본다. 교배는 이 개체와 다른 개체, 즉 총 4개의 tree가 mutation, cross-over 수반한 교배를 한다. 이렇게 생성된 evolved 이미지에 criteria를 적용하여 적자생존의 법칙처럼 적당한 이미지가 걸러지도록 한다.
strcmp Compare two strings Returns an integral value indicating the relationship between the strings: A zero value indicates that both strings are equal. A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite.
printf format tags %[flags][width][.precision][length]specifier
atoi Convert string to integer
On success, the function returns the converted integral number as an int value. If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX or INT_MIN is returned.
StudentRecord record[NStudent];
StudentRecord *record; StudentRecord *record_c;
record = new StudentRecord[NStudent]; // C++ version of allocating a memory block
record_c = (StudentRecord *) malloc (sizeof(StudentRecord)*NStudent); // C version of allocating a memory block // void * malloc ( size_t size );
서 교수님: 두 개의 struct type 데이터에 대해서, A = B;라고 하여 B를 A에 assign 하는 경우 대부분은 성립합니다. 그러나, struct 내부에서 배열을 가지고 있는 경우에는 그렇지 않습니다. 그래서 memcpy() 라는 함수를 사용하여 메모리를 블럭 단위로 카피하는 방법이 있습니다. 이는 음악 CD나 DVD 의 바이너리 카피를 만드는 것과 같은 이치입니다.
Steve Oualline Practical C Prgoramming 6. Decision and Control Statements
calculations, expressions, decision and control statements
control flow linear programs branching statements (cause one section of code to be executed or not executed, depending on a conditional clause) looping statements (are used to repeat a section of code a number of times or until some condition occurs)
"According to the C syntax rules, the else goes with the nearest if."
KISS principle (Keep It Simple, Stupid) : We shoud write code as cleary and simply as possible.
"By adding an extra set of braces, we improve readability, understanding, and clarity."
strcmp Compare two strings : The function compare two strings, and then returns zero if they are equal or nonzero if they are different. : This function starts comparing the first character of each string. If
they are equal to each other, it continues with the following pairs
until the characters differ or until a terminanting null-character is
reached. : Returns an integral value indicating the relationship between the strings: A zero value indicates that both strings are equal. A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite.
ref. Steve Oualline, Practical C Programmin, 292-293p
root node leaves
"Recursion is extremely useful with trees. Our rules for recursion are: 1. The function must make things simpler. This rule is satisfied by trees, because as you descend the hierarchy there is less to search. 2. There must be some endpoint. A tree offers two endpoints, either you find a match, or you reach a null node.
EOF (End-Of-File) the value returned by several <cstdio> functions to
indicate failure, either because the End-of-File has been reached in a
reading operation or because an error happened.
Usage of memcpy function in <string.h> void * memcpy (void * destination, const void * source, size_t num);
size_t Unsigned integral type : the integral data type returned by the language operator sizeof and is defined in the <cstddef> header file (among others) as an unsigned integral type : It expresses a size or count in bytes.
An array is a set of consecutive memory locations used to store data. Each item in the array is called an element. The number of elements in an array is called the dimension of the array. To reference an element of an array, you use a number called the index -- the number inside the square brackets.
Strings are sequences of characters. Strings are just character arrays with a few restrictions.
less = number[1]; for (i=1; i<20; i++) if(less>number[i]){ k = less; less = number[i]; number[i] = k; } // k = number[1]; number[1] = less; // less = k; cout << "number[1]= " << number[1] << endl;
less = number[2]; for (i=2; i<20; i++) if(less>number[i]){ k = less; less = number[i]; number[i] = k; } number[2] = less; cout << "number[2]= " << number[2] << endl;
less = number[3]; for (i=3; i<20; i++) if(less>number[i]){ k = less; less = number[i]; number[i] = k; } number[3] = less; cout << "number[3]= " << number[3] << endl;
그렇다. 난 이 코드가 대단히 비효율적이라는 것 때문에 괴로웠다. 비효율적이라기보다는 하지 않아도 되는 일을 쓸데없이 시키고 있지 않은가. 처음 숙제를 시작할 때부터 알고 있었던 사실이었다. 분명 방법이 있다는 것을 느끼면서도, 무슨 수를 써도 어쩔 수 없어 결국 for 구문 아래에서 swapping을 해야 했던 이유는, index를 기준으로 접근했을 때에는 index를 swapping해야 한다고만 생각하고, element를 기준으로 접근했을 때에는 element의 value를 swapping해야 한다고만 생각했기 때문이었다. 하지만 index를 swapping하자니 for 구문 아래에서 에러가 나고, value를 찾은 다음에는 해당 index를 for 구문 밖으로 빼낼 방법이 없고. 아예 전체 index에 대한 ghost index(?) 같은 걸 만들어야 하나 해서 심지어 실행해 옮기기까지 했던 왕삽질을 거듭했다.
사고에도 시각의 맹점 같은 게 있는 것 같다. 뭔가 있다는 것을 알면서도 죽어도 그게 보이지 않는, 죽어도 그게 생각나지 않는. 결과만 나오면 뭐 하나? 내게 코딩은 수단이지 결코 목적이 아닌 것을. 학교에 온 이유는 여기까지 왔을 때, 사고의 맹점에 다달았을 때, 더 이상 혼자 힘으로는 갈 수가 없다는 것을 수없이 느꼈기 때문이었다. 이런 건 책이나 인터넷 포럼 같은 곳에 나와 있는 것도 아니다. (이 문제는 초보 예제니까 나와 있을지도 모르겠지만. 이 문제가 문제가 아니라 사고력이 문제인 것이다.) 컴퓨터 공학을 전공한 사람이나 직업 프로그래머라고 해서 실마리를 주는 것도 아니었다. 내가 뭐 그렇게 어려운 알고리듬을 원하는 것도 아니건만. (조금은 원하나? 당장이 아니라서 그렇지.) 내가 코딩해서 원하는 결과가 나왔던 40여 개의 코드 중에 정말로 기능적으로 최적이며 응용이 쉽게 만들었다고 느낀 코드는 딱 하나이다. 게다가 그 또한 내 무지에서 비롯된 착각인지도 모른다.
진짜 이거 이렇게 풀어 줄 존재가 절실했다. 실제로 어떤 일들이 벌어지고 있는지 알고 있는 사람이 절실했다. 정확하고 세세하게
알고 있어야 진정 컨트롤할 수 있기 때문이다. 나는 조절력을 가지고 싶다. 많이도 아니다. 내 작업할 수 있는 정도로만. 내가 뭐 지형이나 지질을 파악한댔나, 단지 내가 지도에서 어느 위치에 있는지만 알 수 있으면 만족이다. 초보만 떼면 되는데.
1. swapping 지난 (주어진 데이터 - 수열 - 에서 최대값과 최소값을 구하는) 숙제로 assignment에 대해 완전히 이해했다고 생각했었는데 아니었다. ( ..)^
Swapping two data elements
int a, b, c; a=10; b=20;
How can you exchange the values of the two variables?
이 문제 정말 헤맸음. int c가 선언되어 있어서 힌트가 되었다.
2. address 중간에 방을 세 개나 비워 둔다... 왜 그럴까...? >> ㅎㅎ 비워 두는 거 아니다. number[]와 number는 다른 거 아니었어??? > 아니다. 같은 거다. max와 min을 먼저 만드는 것을 보면 memory는 OS가 main() 함수를 호출하기 이전에 (즉, 프로그램이 실행되기 이전에) 마련되는 것인가? > 아니구나. main() 함수에서 선언된 순서대로인 것이 맞다.
3221223080 0xbffff6a8 10 3221223080 0xbffff6a8 5 3221223080 0xbffff6a8 30 3221223080 0xbffff6a8 93 3221223080 0xbffff6a8 0 3221223080 0xbffff6a8 84 3221223080 0xbffff6a8 65 3221223080 0xbffff6a8 3 3221223080 0xbffff6a8 78 3221223080 0xbffff6a8 67 3221223080 0xbffff6a8 45 3221223080 0xbffff6a8 12 3221223080 0xbffff6a8 28 3221223080 0xbffff6a8 75 3221223080 0xbffff6a8 111 3221223080 0xbffff6a8 3 3221223080 0xbffff6a8 845 3221223080 0xbffff6a8 41 3221223080 0xbffff6a8 343 3221223080 0xbffff6a8 43 address=3221223080 (bffff6a8) = 10 address=3221223080 (bffff6a8) = 5 address=3221223080 (bffff6a8) = 30 address=3221223080 (bffff6a8) = 93 address=3221223080 (bffff6a8) = 0 address=3221223080 (bffff6a8) = 84 address=3221223080 (bffff6a8) = 65 address=3221223080 (bffff6a8) = 3 address=3221223080 (bffff6a8) = 78 address=3221223080 (bffff6a8) = 67 address=3221223080 (bffff6a8) = 45 address=3221223080 (bffff6a8) = 12 address=3221223080 (bffff6a8) = 28 address=3221223080 (bffff6a8) = 75 address=3221223080 (bffff6a8) = 111 address=3221223080 (bffff6a8) = 3 address=3221223080 (bffff6a8) = 845 address=3221223080 (bffff6a8) = 41 address=3221223080 (bffff6a8) = 343 address=3221223080 (bffff6a8) = 43 Their sum is 1981 Their max is 845 Their min is 0 Address of the variable max is 0xbffff6a0 Address of the variable min is 0xbffff6a4
sum의 address를 첨가하면,
Address of the variable sum is 0xbffff69c
그렇다면, int sum이 가장 먼저 생성된다.
쉘에서 다시 실행시키면,
3221223816 0xbffff988 10
3221223816 0xbffff988 5 3221223816 0xbffff988 30 3221223816 0xbffff988 93 3221223816 0xbffff988 0 3221223816 0xbffff988 84 3221223816 0xbffff988 65 3221223816 0xbffff988 3 3221223816 0xbffff988 78 3221223816 0xbffff988 67 3221223816 0xbffff988 45 3221223816 0xbffff988 12 3221223816 0xbffff988 28 3221223816 0xbffff988 75 3221223816 0xbffff988 111 3221223816 0xbffff988 3 3221223816 0xbffff988 845 3221223816 0xbffff988 41 3221223816 0xbffff988 343 3221223816 0xbffff988 43 address=3221223816 (bffff988) = 10 address=3221223816 (bffff988) = 5 address=3221223816 (bffff988) = 30 address=3221223816 (bffff988) = 93 address=3221223816 (bffff988) = 0 address=3221223816 (bffff988) = 84 address=3221223816 (bffff988) = 65 address=3221223816 (bffff988) = 3 address=3221223816 (bffff988) = 78 address=3221223816 (bffff988) = 67 address=3221223816 (bffff988) = 45 address=3221223816 (bffff988) = 12 address=3221223816 (bffff988) = 28 address=3221223816 (bffff988) = 75 address=3221223816 (bffff988) = 111 address=3221223816 (bffff988) = 3 address=3221223816 (bffff988) = 845 address=3221223816 (bffff988) = 41 address=3221223816 (bffff988) = 343 address=3221223816 (bffff988) = 43 Their sum is 1981 Their max is 845 Their min is 0 Address of the variable max is 0xbffff980 Address of the variable min is 0xbffff984 Address of the variable sum is 0xbffff97c
아항~ memory의 주소는 compile할 때 할당되고, update를 하더라도 기존 주소를 그대로 찾아간다. 맞나??? > 틀리다. 그냥 그렇게 보였을 뿐. (메모리를 달리 사용하고 있지 않았기 때문이었다.) 여하간, 도대체 왜! sum, max, min이 먼저 만들어지고 나서 number[]가 만들어지는 것이야??? > 변수들의 형태에 따라서 분류하여 그 순서대로 만들기 때문이란다.
뜬금없이 제일 마지막에 int why 변수를 하나 첨가해 보았더니, (Xcode 실행창)
3221223084 0xbffff6ac 10 3221223084 0xbffff6ac 5 3221223084 0xbffff6ac 30 3221223084 0xbffff6ac 93 3221223084 0xbffff6ac 0 3221223084 0xbffff6ac 84 3221223084 0xbffff6ac 65 3221223084 0xbffff6ac 3 3221223084 0xbffff6ac 78 3221223084 0xbffff6ac 67 3221223084 0xbffff6ac 45 3221223084 0xbffff6ac 12 3221223084 0xbffff6ac 28 3221223084 0xbffff6ac 75 3221223084 0xbffff6ac 111 3221223084 0xbffff6ac 3 3221223084 0xbffff6ac 845 3221223084 0xbffff6ac 41 3221223084 0xbffff6ac 343 3221223084 0xbffff6ac 43 address=3221223084 (bffff6ac) = 10 address=3221223084 (bffff6ac) = 5 address=3221223084 (bffff6ac) = 30 address=3221223084 (bffff6ac) = 93 address=3221223084 (bffff6ac) = 0 address=3221223084 (bffff6ac) = 84 address=3221223084 (bffff6ac) = 65 address=3221223084 (bffff6ac) = 3 address=3221223084 (bffff6ac) = 78 address=3221223084 (bffff6ac) = 67 address=3221223084 (bffff6ac) = 45 address=3221223084 (bffff6ac) = 12 address=3221223084 (bffff6ac) = 28 address=3221223084 (bffff6ac) = 75 address=3221223084 (bffff6ac) = 111 address=3221223084 (bffff6ac) = 3 address=3221223084 (bffff6ac) = 845 address=3221223084 (bffff6ac) = 41 address=3221223084 (bffff6ac) = 343 address=3221223084 (bffff6ac) = 43 Their sum is 1981 Their max is 845 Their min is 0 Address of the variable max is 0xbffff6a0 Address of the variable min is 0xbffff6a4 Address of the variable sum is 0xbffff69c Address of the variable why is 0xbffff6a8
헉!!! 주소 바꾼다... 도대체 뭣이야... 점점 더 이해 안 가. ㅜㅜ 어쨌든, update 시 변경 사항이 있으면 compile 후 주소를 바꿔치기도 하는 등 각 변수에게 고정된 주소를 주는 것이 아니구나.
서 교수님: 컴파일러가 C 소스코드를 분석해서 기계어로 바꾸는데, 소스코드 전체를 들여다 보면 변수들이 여럿 나오겠지요. 단일 변수들은
단일 변수들로 배치할 것이고 어레이로 선언된 것들은 따로 배치해서 메모리를 할당하게 되어 있을 겁니다. 물론 어떤 컴파일러는
그렇지 않고 다른 방법을 사용할 수도 있습니다. 그래서, number의 어드레스가 다른 변수들과 달리 나중의 주소를 가지게
되는 것으로 판단됩니다.
number[10] 이라고 배열 선언을 하면 컴파일러는 10개의 연속된 데이터를 위한 공간을 확보하고 그 첫번째 공간의 주소를 number 에 넣습니다. 그래서 number 는 number[0] 의 주소를 가지는 것입니다.
number[1] 은 배열에서 number[0] 다음의 값을 가지는데 그 공간의 주소값을 알고 싶으면 &number[1] 이라고 하든지 number+1 이라고 하면 됩니다.
꺼꾸로, number 에서 시작하여 두 번째 즉 number[1] 의 값을 주소로부터 얻고 싶으면 number[1] 이라고 하든지 *(number+1) 로 하여 얻을 수 있습니다.
서 교수님: 각 변수들의 실제 메모리 주소 (physical address) 는 프로그램이 실행되는 시점에서 결정됩니다. 적당한 메모리 위치에 OS 가 실행프로그램을 통째로 카피하고, CPU가 main() 의 첫 부분부터 실행하도록 합니다. 다른 프로그램들이 자주 실행되고 끝나는 상황이라면 변수들의 주소가 거의 매번 다르게 보일 것입니다. 그래서, 실제 주소를 지정하는 방법은 거의 없습니다.
서 교수님: 변수들이 몇 개가 있는지 어떤 형태인지를 컴파일러가 모두 조사한 후에 각 변수들에 필요한 메모리를 미리 할당해 둡니다. 이때는 상대적인 메모리 주소를 사용하죠. 소스코드에서는 변수들의 선언 순서가 중요합니다. 그러나, 실제로 실행되는 상황에서는 이미 필요한 모든 변수들이 메모리를 차지하고 있는 상황이 됩니다.
서 교수님: C/C++ 프로그래밍은 컴퓨터 구조에 대해서 약간 알고 있으면 훨씬 더 쉽게 접근할 수 있습니다.
3.
교수님 강조: 문제의 풀이를 순차적인 언어로 표현할 수 있으면, 그것을 프로그래밍 언어로 바꿀 수 있다.
4.
warning: control reaches end of non-void function
무슨 뜻인가 했더니 > It means that you have to return a value using the return statement
before the end of your function. This does not apply to void functions
because a void function does not return a value. -> omission으로 함수의 return 값을 지정해 주지 않았을 때 생기는 경고였다.
5.
int *address;
int printf ( const char * format, ... ); %[flags][width][.precision][length]specifier * The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. > 난 이거 아직 이해 못 했다.
6.
address = &max;
& 2) A symbol used to precede a variable name (as in &x). Means the address of the named variable (address of x). Used to assign a value to a pointer variable.
The basic elements of a program are the data declarations, functions, and comments.
main() 함수는 첫번째로 호출되는 함수이며, 이 main 함수가 다른 함수들을 직접 또는 간접으로 호출한다.
return(0);는 프로그램이 정상적으로 (Status=0) 존재했었음을 OS에게 보고하기 위해 쓰인다. : return value가 클수록 error가 심각하다는 뜻이다.
Variables Each variable has a variable type. A variable must be defined in a declaration statement just before the main() line at the top of a program.
Assignment statements The general form of the assignment statement is: variable = expression; The = is used for assignment.
printf Function printf : a standard function to output our message Print formatted data to stdout Writes
to the standard output (stdout) a sequence of data formatted as the
format argument specifies. After the format parameter, the function
expects at least as many additional arguments as specified in format. The format tags follow this prototype: %[flags][width][.precision][length]specifier
: 표준 입출력 함수- 표준 입출력 장치를 통해 데이터를 입력하거나 출력하는 기능을 갖고 있는 함수 - 표준 입출력 함수를 사용하려면 #include <stdio.h>를 기술해 줘야 한다. [형식] printf(" 출력양식 ", 인수1,인수2...); - 서식문자열에는 모든 문자를 사용할 수 있으며 변환문자와 제어문자를 제외하고는 화면에 그대로 출력 - 인수와 변환문자는 일대일 대응해야 하며 반드시 인수의 자료형과 문자의 자료형은 일치해야 한다. ex) printf("%d + %d= %d\n",10,20,30); 출력결과 10+20=30
stdout Standard output stream : the default destination of regular output for applications. It is
usually directed to the output device of the standard console
(generally, the screen).
cf. library fuctions
%d : integer conversion specification
parameter list
The general form of the printf statement is: printf(format, expression-1, expression-2, ...); where format is the string describing what to point.
1. input.txt 파일에 20개의 정수를 임의로 입력하여 작성하시오. 2. 프로그램을 수정하여 입력 데이터 파일의 합을 구하는 프로그램을 작성하시오. 3. 최대값과 최소값을 구하는 루틴을 첨가하시오.
Xcode에서 프로젝트를 만들어 코딩할 경우, 파일명이나 폴더명을 함부로 바꾸면 (아마도 소유권 문제로) 실행이 되지 않을 수 있다. 이 경우 "no launchable executable present at path"라는 메시지가 뜬다. 쉘에서 "chmod +x 파일이름"을 친 이후 다시 컴파일하면 가능하다. 그러나 여전히 XCode 내부에서 실행시킬 수는 없었다. 얼마나 당황스러웠는지 새로 프로젝트를 만들 생각을 아예 못 한... 나는 초짜라 그런지 코딩은 재밌는 것 같은데 XCode 등이 토대로 하는 세계관(?? ㅡㅡ; )이나 컴퓨터 자체가 무섭다.
FileIn.open로 읽어 들일 파일은 XCode에서는 debug 폴더 안에, shell에서 실행시킬 때에는 .cpp 실행파일이 있는 폴더 안에 넣어 줘야 한다.
이번 숙제 엄청 간단한 거였는데 굉장히 오랜 시간이 걸렸다. 그 중 90%는 코딩이 아니라 인터페이스에 익숙치 않아 생긴 초삽질성 장애들. ㅡㅡ; 물론 처음에는 for 구문 안에 for 구문을 돌리는 등 헤매였지만... 아래 그 적나라한 흔적. (마음이 급하면 우선 손익은 Python에 기대게 된다.) 어쨌든 assignment라는 게 얼마나 고마운 건지 처음으로 알았다. 마구마구 업뎃이 되는구나. 그전에는 왕 무시했었는데.
list = [5,2,1,6,10,3,80]
max = list[0]
for i in range(6):
#for i in range(6): ### print list[i] ## for j in range(4): ## if list[i] > list[j]:
statement (문장) - A statement will have internal components (eg, expressions). - Many languages (e.g. C)
make a distinction between statements and definitions, with a statement
only containing executable code and a definition declaring an
identifier. : An instruction written in a high-level language. - Programs consist of statements and expressions.An expression is a group of symbols that represent a value. - Statements do not return results and are executed solely for their side effects, while expressions always return a result and often do not have side effects at all.
* statement block: begin WRITE('Number? '); READLN(NUMBER); end * if-statement: if A > 3 then WRITELN(A) else WRITELN("NOT YET") end * switch-statement: switch (c) { case 'a': alert(); break; case 'q': quit(); break; } * while-loop: while NOT EOF DO begin READLN end * do-loop: do { computation(&i); } while (i < 10); * for-loop: for A:=1 to 10 do WRITELN(A) end
expression (式) : a combination of values, variables, operators, and functions : any legal combination of symbols that represents a value : 프로그래밍 작성 언어에서 어떤 값을 계산하는 숫자, 변수, 함수 호출 결과 및 이들이 연산자에 의해 조합된 것. 예를 들어 100, x, x+y, sin(y*2), y>100 등은 모두 식이다. 그 결과값의 형에 따라 산술식, 논리식, 문자열식 등이 있다. - Each programming language and application has its own rules for what is legal and illegal. - Every expression consists of at least one operand and can have one or more operators. Operands are values, whereas operators are symbols that represent particular actions. - The expression is (or can be said to have) its evaluated value; the expression is a representation of that value. - Expressions are often classified by the type of value that they represent. For example:
# Boolean expressions : Evaluate to either TRUE or FALSE # integer expressions: Evaluate to whole numbers, like 3 or 100 # Floating-point expressions: Evaluate to real numbers, like 3.141 or -0.005 # String expressions: Evaluate to character strings
declaration (宣言) - a declaration specifies a variable's dimensions, identifier, type, and other aspects. It is used to announce the existence of a variable or function. - For variables, definitions assign bits to an area of memory that was
reserved during the declaration phase. For functions, definitions
supply the function body. It is thus clear that while a variable or
function may be declared many times, it must only be defined once. (1) 어떤 언어의 원시 프로그램에서 그 프로그램의 인터프리터에 필요한 정보, 특히 프로그램에서 실행 시 사용될 자료의 특성을 전달하기 위한 표현 방법. (2) 프로그램에서 변수, 프로시저, 함수 등의 이름과 그 자료 유형, 함수의 반환값, 함수나 프로시저의 인자와 그 몸체를 정의하는 것. 특히 프로그램에서 쓰이는 변수의 형을 정의하는 것을 말한다.
Non-Uniform Random Variate Generation (originally published with Springer-Verlag, New York, 1986) Luc Devroye School of Computer Science McGill University
III. DISCRETE RANDOM VARIATES 83 1. Introduction. 83 2. The inversion method. 85 2.1. Introduction. 85 2.2. Inversion by truncation of a continuous random variate. 87
The word entheogen is derived from the ancient Greek : ἔνθεος (entheos) and γενέσθαι (genesthe). Entheos
literally means "god (theos) within", translates as "inspired" and is
the root of the English word "enthusiasm". The Greeks used it as a term
of praise for poets and other artists. Genesthe
means "to generate". So an entheogen is "that which generates God (or
godly inspiration) within a person". (중략) It was coined as a
replacement for the terms "hallucinogen" (popularized by Aldous Huxley's experiences with mescaline, published as The Doors of Perception in 1953) and "psychedelic" (a Greek neologism for "mind manifest", coined by psychiatrist Humphry Osmond,
who was quite surprised when the well-known author, Aldous Huxley,
volunteered to be a subject in experiments Osmond was running on
mescaline). Ruck et al. argued that the term "hallucinogen" was
inappropriate due to its etymological relationship to words relating to
delirium and insanity. The term "psychedelic" was also seen as problematic, due to the similarity in sound to words pertaining to psychosis and also due to the fact that it had become irreversibly associated with various connotations of 1960spop culture.
(아~ 또 삼천포. 그만 가야지...)
keywords: random, Brownian motion, Tydall effect, random walk, mean square distance, Monte Carlo (여기에도 나오네... 적분 방법 아니었어?), pseudo-random number generators (그래 이게 목적이겠지만.), Molecular Dynamics (MD) 방법 (방법??), self-avoiding random walk (SAW), Flory 이론, Nienhuis (??), persistent random walk, limited random walk, fractal growth, DLA (Diffusion Limited Aggregates), Chaos Game, Iterated Function System, Theory of Affine Map (->Image Processing), Benoit Mandelbrot, Fractal Geometry, Hausdorff Dimension, Koch 곡선, Box counting algorithm (Capacity dimension), 'Mountains Never Existed',
MC(Monte Carlo) code:
if randN(m) < 0.5,
Point(m) = Point(m)+1;
else
Point(m) = Point(m)-1;
end;
randN = rand(N) : Generate N random number between 0 and 1
MC 방법의 응용 * random walks, fractal growth, * Equilibrium/non-equilibrium statistical phenomena, phase transition * neural networks * particle scattering with the help of computers * optimization 나는 particle scattering 때문에 자주 본 거였구만.
RAND(N) (0.0,1.0)사이의 균일한 분포를 가진 마구잡이 수로 이루어진 NxN 행렬 그럼 프로세싱에서의 random()인 건가...? 분포가 다른 건가?
S = RAND('state') 현재상태를 포함한 35-element 벡터. RAND('state',S) resets the state to S. RAND('state',0) resets the generator to its initial state. RAND('state',J), for integer J, resets the generator to its J-th state. RAND('state',sum(100*clock)) resets it to a different state each time. 포기.
ref. K. Kremer and T. W. Lyklema, Phys. Rev. Lett. 55, 9091 (1985) T. M. Bishtein, S. V. Buldyrev, and A. M. Elyashivitch, Polymer 26, 1814 (1985)
Fractal Growth
- 평형으로부터 멀리 떨어진 현상 (far from equilibrium)
- 시공간적으로 매우 다양한 형태
- 해석적 연구가 매우 어려움
프랙탈 성장의 예
- 금속이온의 전기화학적 흡착에 의한 뭉침
- 고분자, 세라믹, 유리, 얇은막의 성장
- Viscous fingering
- Dielectric breakdown
- 박테리아의 성장
- 신경세포의 성장
* 성장규칙 o 평면상의 움직이지 않는 씨앗으로부터 시작. o 멀리 떨어진 곳으로부터 시작하여 마구 걷기를 수행. o 마구 걷기가 씨앗을 만나면 붙음. o 다시 마구걷기를 반복함._M#]
Mountains Never Existed
Iterated Function System
The concept of the Iterated Function System was invented by creative fractal genius Michael Barnsley. An IFS is composed of a few simple elements: transformations and probabilities. The transformations are usually expressed as matrices--one translational matrix and one transformational matrix. This sounds a bit dry, but actually the concept is a bit more interesting than all that. For the Sierpinski Triangle, the transformations are simple, and are better expressed as rules in a recursive procedure:
Begin by selecting three vertices in the two-dimensional plane. Note their coordinates. Next, select an initial point--best if within the bounds of the triangle formed by the three vertices, but this is not a requirement. The main procedure goes as follows.
Select one of the three vertices at random.
Roll a six sided die and integer-divide by two, flip three coins and take the exception, or ask a friendly computer for help.
From the current location of the point, calculate the midpoint of the line connecting the point and the vertex just selected.
Move to this midpoint, and plot the point.
Iterate ad infinitum.
That's it! Sierpinski's Triangle. To get any sort of worthwhile picture, of course, hundreds to thousands of points need to be plotted. In fact, usually the first twenty or so points are off track and need not be plotted. However, the algorithm outlined above is amazingly simple to do, and incredibly easy to implement on any machine. I have written Sierpinski programs for every graphing calculator under the sun, as well as for most desktop computers as well. Try
it yourself in BASIC or on a graphing calculator. You'll surprise yourself at how easy it is to impress people with a graphing calculator. :)
How Long is the Coast?
A long, long time ago, fractal god Benoit Mandelbrot posed a whimsical question: How long is the coastline of Britain? His mathematical colleagues were miffed, to say the least, at such annoying waste of their amazing computation powers on this insignificant minutae. They told him to look it up.
Of course, Mandelbrot had a reason for his peculiar question. Quite an interesting reason. Look up the coastline of Britain yourself, in some encyclopedia. Whatever figure you get, it is wrong. Quite simply, the coastline of Britain is infinite. You protest that this is impossible. Well, consider this. Consider looking at Britain on a very large-scale map. Draw the simplest two-dimensional shape possible, a triangle, which circumscribes Britain as closely as possible. The perimeter of this shape approximates the perimeter of Britain.However, this area is of course highly inaccurate. Increasing the amount of vertices of the shape going around the coastline, and the area will become closer. The more vertices there are, the closer the circumscribing line will be able to conform to the dips and the protrusions of Britain's rugged coast.There is one problem, however. Each time the number of vertices increases, the perimeter increases. It must increase, because of the triangle inequality. Moreover, the number of vertices never reaches a
maximum. There is no point at which one can say that a shape defines the coastline of Britain. After all, exactly circumscribing the coast of Britain would entail encircling every rock, every tide pool, every pebble which happens to lie on the edge of Britain. Thus, the coastline of Britain is infinite.
The dependence of length (or area) measurements on scale poses great problems for biologists who need to use the results. For example, lakes that have a very convoluted shoreline are known to offer more area of shallows in relation to their total surface area, and thus support richer communities of plant and animal life. Attempts to characterize shore-line communities in terms of indexes that relate water surface to shoreline length have been frustrated by problems of scale.
Fractal dimension
The notion of "fractional dimension" provides a way to measure how rough fractal curves are. We normally consider lines to have a dimension of 1, surfaces a dimension of 2 and solids a dimension of 3. However, a rough curve (say) wanders around on a surface; in the extreme it may be so rough that it effectively fills the surface on which it lies. Very convoluted surfaces, such as a tree's foliage or the internal surfaces of lungs, may effectively be three-dimensional structures. We can therefore think of roughness as an increase in dimension: a rough curve has adimension between 1 and 2, and a rough surface has a dimension somewhere between 2 and 3. The dimension of a fractal curve is a number that characterizes the way in which the measured length between given points increases as scale decreases. Whilst the topological dimension of a line is always 1 and that of a surface always 2, the fractal dimension may be any real number between 1 and 2. The fractal dimension D is defined by
log ( L2 / L1 )
D = --------------- ... (1)
log ( S1 / S2 )
where L1, L2 are the measured lengths of the curves (in units), and S1, S2 are the sizes of the units (i.e. the scales) used in the measurements.
Van Koch Curve
This is the Von Koch curve. Its construction is almost as easy as the Sierpinski Triangle. You start with a triangle (equilaterality is really more important in this case than for the Sierpinski Triangle), and, on each side, tack on little equilateral triangles, so you end up with a shape very much like a Star of David. The Star of David has six little triangles sticking out. For each triangle, repeat the previous process. Iterate infinitely.
Recall that when we discussed the Koch Curve in figure 4(b), we had four chunks that were small copies of the whole curve. Each chunk could be magnified by 3 to return a copy the same size as the original curve. Plugging these values into the above equation, we get
Ds = log4 /log3= 1.262
This is a value we would have expected. Because the curve is more intricate than a 1-dimensional line segment (it wanders around on the plane some), we would expect its fractal dimension to be greater than 1. But it doesn't come very close to filling an area of the 2-dimensional plane, so we would expect the curve's fractal dimension to be much smaller than 2. The Koch Curve is indeed a fractal. It is self-similar and it has a fractional dimension of about 1.262.
Sierpinsky Gasket
Now the Sierpinski Gasket of figure 2 comes a little closer to filling a 2-dimensional triangle, so we will expect it to have a fractal dimension closer to 2. Recall that we have 3 subtriangles that can be magnified by 2 to get back a copy the same size as the original. Plugging those values into the Self-Similarity dimension equation, we get
Ds = log3/log2= 1.585
The Sierpinski Gasket is therefore a fractal--It is self-similar and its fractional dimension is about 1.585. We have now investigated two bonafide fractals. Both the Sierpinski Gasket and the Koch Curve satisfy Devaney's two criteria for being a fractal: self-similarity and fractional dimension.
break
Break is used within loops and switch statements to jump to the end of the
code block. It causes the "//code..." above to be skipped and terminates the
loop. In switch case statements, break causes the remaining cases to be
skipped--it prevents "falling through" to other cases. 호~ 나도 이거 필요한 적 많았는데... continue to jump to the top of the loop block 그럼 왜 continue라고 불러?? for
goto You cannot, for instance, jump into the middle of a function from a different function by using goto.
switch The prevent falling through, include break;at the end of any code block. 신기하다!
#include Generally, it is
necessary to tell the preprocessor where to look for header files if they are
not placed in the current directory or a standard system directory.
include file (짜넣기 파일) : 복수의 프로그램이 공통으로 사용하는 정수나 영역 등에 대해서 그 속성을 뜻매김한 정보를 저장하고 있는 파일.
ifstream Input file stream class The file to be associated with the stream can be specified either as a parameter in the constructor or by calling member open.
File I/O
file I/O in C++ C++ has two basic classes to handle files, ifstream and ofstream. To
use them, include the header file fstream. Ifstream handles file input
(reading from files), and ofstream handles file output (writing to
files).
file I/O in C For C File I/O you need to use a FILE pointer, which
will let the program keep track of the file being accessed. (You
can think of it as the memory address of the file or the location
of the file).
질문>> main() 함수에 대하여
main() 함수란?
서 교수님: main() 함수는 시스템 (오퍼레이팅 시스템: OS) 이 호출하는 함수이기 때문에 미리 리턴 타입을 정해 둔 것입니다.
또 이 함수의 첫번째 문장부터 수행되도록 미리 정해져 있습니다. 그래서, main() 이 없는 C 프로그램은 컴파일 에러가
나고 main() 여러 개가 있어도 에러가 나옵니다.
그리고, 좀 더 복잡한 프로그램에서는 외부 실행 파일을 직접 호출하여 사용하기도 합니다. 그런한 경우 main() 의 리턴값에 따라 수행결과를 판단할 수 있어요.
최근의 컴파일러 출력을 보면 C/C++ 의 main() 함수는 int 를 리턴하는 것으로 규정되어 있습니다. 그래서
int main ()
이라고 선언을 하죠. 그래서, 이 함수가 끝날 때에는 항상 return return_val; 가 들어가야 합니다. return_val은 에러가 없을 경우 통상적으로 0 을 주면 됩니다.
main() 함수 안에서 exit(0); 과 return 0; 는 같은 역할을 합니다.
컴파일할 때 아래와 같이 하면 int main() 으로 해야 된다고 경고가 나올 것입니다.
g++ V2008122-01.cpp -o V2008122-01 -Wall
main() 함수를 선언할 때 리턴 타입을 정해 주지 않으면 다음과 같은 오류 메시지가 뜬다.
/Users/lym/cintro/week1/V2008122-01.cpp:16: warning: ISO C++ forbids declaration of 'main' with no type
질문>> "int argc, char *argv[]"에 대하여
int main(int argc, char *argv[]) 에서 main 다음 괄호 안의 것들은 command line argument라고 부른다.
cf. 교재 201쪽 The parameter argc is the number of arguments on the command line including the program name. The array argv contains the actual arguments.
argument : a value that is passed to a routine
- In programming, a value that you pass to a routine.
For example, if SQRT is a routine that returns the square root of a
value, then SQRT(25) would return the value 5. The value 25 is the
argument.
Argument is often used synonymously with parameter, although parameter can also mean any value that can be changed. In addition, some programming languages
make a distinction between arguments, which are passed in only one
direction, and parameters, which can be passed back and forth, but this
distinction is by no means universal.
An argument can also be an option to a command, in which case it is often called a command-line argument.
parameter : a variable which takes on the meaning of a corresponding argument passed in a call to a subroutine.
c. 터미널에서 "./V2008122-01 input.txt"라고 치면 다음과 같이 나옵니다.
argc=2 argv[0]=./V2008122-01 argv[1]=input.txt
서 교수님: main(argc, argv[])에서 argv[0] = 실행프로그램 이름; 1번째는 항상 실행프로그램의 패스/이름 이 들어갑니다.
매개변수를 터미널에서 입력하는 것은 사람이 입력하지만, 사실은 shell 프로그램이 fileio 함수를 호출할 때 매개변수로 주는 것이고, 좀 더 엄밀하게는 OS가 main 함수를 호출할 때 주는 것입니다.
나는 argv[0]라는 게 굉장히 tricky하게 느껴진다. 그럼 자기 자신을 매개변수로 갖는다는 말 아닌가? 완전... '내 이름을 불러 주오~'잖아.
아~
교수님께서 말씀하셨던 fileio.exe가 내 경우 week1.exe이구나... 내가 새 프로젝트(week1)를 만들어서 다시
작성했기 때문에. Xcode에서는 프로젝트명으로 실행파일이 만들어지고 그것은 자동으로 Debug 폴더에 자리를 잡는다. 그러므로
다음과 같이 들어가서 치면 된다. 헤매인 끝에, 나는 week1폴더에 .cpp파일을 만들어 컴파일했으므로
V2008122-01.exe가 만들어졌던 것을 썼던 것인데. Xcode와 쉘에서의 접근 경로가 이번에도 다르다.
999:~/cintro/week1/build/Debug lym$ ./week1 input.txt Their sum is 1969. The maximum number is 999. The minimum number is 1. argc=2 argv[0]=./week1 argv[1]=input.txt
질문>> "using namespace std;"에 대하여
서 교수님: 한 개의 프로그램에서 여러 개의 동일한 이름을 가지는 함수를 사용하게 될 때namespace 라는 것을 사용하여 구분하기 쉽도록 한 것입니다. C++ 의 한 가지 기능입니다.
그 줄 (using namespace std;) 은
#include <fstream>
#include <iostream>
이 있을 때 포함시키면 편리합니다.
(1) using namespace std; 을 사용하고 싶지 않은 경우 (2) 다른 헤더파일에서도 ifstream, cout, endl 등의 함수를 정의하고 있어서 그 함수들을 사용할 때 구별이 필요한 경우 다음과 같이 하면 됩니다.
Reductionism is the idea that a system can be understood by examining its individual parts. (Implicit in this idea is that one may have to examine something at multiple levels.)
Traditional scientists study two types of phenomena: agents and interactions of agents.
1) 환원주의적 접근으로 해부하기 2) 보다 넓은 시야로 전체 집합을 이해하기 - 몇 개의 agents가 전체적인 패턴을 형성하는지 (예) 뇌세포:인간 지능) 3) 1과 2의 사이에서 agents 간의 상호작용을 연구하기 - The interactions of agents can be seen to form the glue that binds one level of understanding to the next level.
1.1 Simplicity and Complexity
emergent의 예: 개미 굴/군집, 예측을 벗어나는 경제 시장, 척추동물의 패턴 인식 능력, 바이러스와 박테리아에 저항하는 인간의 면역 체계, 지구 생명체의 진화 => 간단한 단위들로 이루어져 있는데 결합하면 전체적으로 복잡한 형상을 띤다. => 단지 부분들의 합으로는 설명할 수 없는 거대한 체계를 이룬다.
The whole of the system is greater than the sum of the parts(, which is a fair definition of holism -- the very opposite of reductionism).
Agents that exist on one level of understanding are very different from agents on another level. Yet the interactions on one level of understanding are often very similar to the interactions on other levels.
상사12 (相似) 「명」「1」서로 모양이 비슷함. 「2」『생』종류가 다른 생물의 기관이 발생적으로 기원과 구조가 다르나 형상과 작용이 서로 일치하는 현상. 예를 들면, 새의 날개와 벌레의 날개 관계, 또는 잎이 변하여 된 완두콩의 덩굴손과 줄기가 변하여 된 포도 나무의 덩굴손 관계 따위이다. 「3」『수1』=닮음〔1〕. 「참」상동04(相同).
ref. 표준국어대사전
# 예측불능성 (unpredictability) 예) 주식 시장, 날씨
# 복잡성 complexity 예) 개미 군, 인간 뇌, 경제 시장 => By self-organizing, complex behavior of collectives is much richer than the behavior of the individual component units.