Nice programing

프랙탈을 프로그래밍하는 방법?

nicepro 2020. 11. 1. 18:38
반응형

프랙탈을 프로그래밍하는 방법?


나는 프랙탈 프로그래밍에 대한 경험이 없습니다. 물론 유명한 Mandelbrot 이미지 등을 보았습니다.

프랙탈에 대한 간단한 알고리즘을 제공 할 수 있습니까?

프로그래밍 언어는 중요하지 않지만 저는 액션 스크립트, C #, Java에 가장 익숙합니다.

나는 내가 프랙탈을 검색하면 많은 (복잡한) 정보를 얻지 만 간단한 알고리즘으로 시작하여 그것을 가지고 놀고 싶다는 것을 알고 있습니다.

기본 알고리즘을 개선하기위한 제안 (예 : 사랑스러운 색상으로 만드는 방법 등)도 환영합니다.


만델 브로트를 프로그래밍하는 것은 쉽습니다.
내 퀵 앤 더티 코드는 다음과 같습니다 (버그가 없다는 보장은 없지만 좋은 개요).

개요는 다음과 같습니다. Mandelbrot 세트는 반경 2의 원 내에 완전히 컴플렉스 그리드에 있습니다.

따라서 직사각형 영역의 모든 지점을 스캔하여 시작하십시오. 각 점은 복소수 (x + yi)를 나타냅니다. 이 복소수를 반복합니다.

[new value] = [old-value]^2 + [original-value] 두 가지를 추적하면서 :

1.) 반복 횟수

2.) 원점에서 [새 값]까지의 거리.

최대 반복 횟수에 도달하면 완료된 것입니다. 원점으로부터의 거리가 2보다 크면 완료된 것입니다.

완료되면 수행 한 반복 횟수에 따라 원본 픽셀에 색상을 지정합니다. 그런 다음 다음 픽셀로 이동합니다.

    public void MBrot()
    {
        float epsilon = 0.0001; // The step size across the X and Y axis
        float x;
        float y;
        int maxIterations = 10; // increasing this will give you a more detailed fractal
        int maxColors = 256; // Change as appropriate for your display.

        Complex Z;
        Complex C;
        int iterations;
        for(x=-2; x<=2; x+= epsilon)
        {
            for(y=-2; y<=2; y+= epsilon)
            {
                iterations = 0;
                C = new Complex(x, y);
                Z = new Complex(0,0);
                while(Complex.Abs(Z) < 2 && iterations < maxIterations)
                {
                    Z = Z*Z + C;
                    iterations++;
                }
                Screen.Plot(x,y, iterations % maxColors); // depending on the number of iterations, color a pixel.
            }
        }
    }

빠진 세부 사항은 다음과 같습니다.

1.) 복소수의 제곱이 무엇이며 어떻게 계산하는지 정확히 알아보십시오.

2.) (-2,2) 직사각형 영역을 화면 좌표로 변환하는 방법을 알아 봅니다.


실제로 Mandelbrot 세트로 시작 하고 그것이 실제로 무엇인지 이해해야합니다.

그이면의 아이디어는 비교적 간단합니다. 복잡한 변수의 함수로 시작합니다.

f (z) = z 2 + C

여기서 z는 복소수 변수 이고 C는 복소수 상수 입니다. 이제 z = 0에서 시작하여 반복합니다. 즉, z 1 = f (0), z 2 = f (z 1 ), z 3 = f (z 2 ) 등을 계산합니다. 시퀀스 z 1 , z 2 , z 3 , ...이 제한 되는 상수 C 세트 , 즉 무한대로 가지 않는 것은 Mandelbrot 세트입니다 (위키 백과 페이지의 그림에서 검은 색 세트).

실제로 Mandelbrot 세트를 그리려면 다음을 수행해야합니다.

  • 복잡한 평면에서 직사각형을 선택합니다 (예 : 점 -2-2i에서 점 2 + 2i로).
  • 모니터의 픽셀에 매핑되는 적절한 직사각형 포인트 그리드 (예 : 400x400 포인트)로 직사각형을 덮습니다.
  • 각 포인트 / 픽셀에 대해 C를 해당 포인트로 지정하고, 예를 들어 해당 반복 시퀀스 z 1 , z 2 , z 3 , ...의 20 개 항을 계산 하고 "무한대로 이동"하는지 확인합니다. 실제로는 반복하는 동안 20 개 항 중 하나의 절대 값이 2보다 큰지 확인할 수 있습니다 (항 중 하나에 해당하는 경우 후속 항은 제한되지 않음이 보장됨). z_k가 있으면 시퀀스는 "무한대로 이동"합니다. 그렇지 않으면 제한된 것으로 간주 할 수 있습니다.
  • 특정 지점 C에 해당하는 시퀀스가 ​​경계가 지정되면 그림에 해당 픽셀을 검은 색으로 그립니다 (만델 브로트 세트에 속하기 때문에). 그렇지 않으면 다른 색으로 그립니다. 재미 있고 예쁜 플롯을 만들고 싶다면 복근 (20 기)의 크기에 따라 다른 색으로 그려보세요.

프랙탈에 대한 놀라운 사실은 우리가 쉽고 명백하게 무해한 요구 사항 에서 엄청나게 복잡한 세트 (특히 Mandelbrot 세트 경계)얻을 수있는 방법 입니다.

즐겨!


복소수가 골칫거리 인 경우 L- 시스템을 사용하여 공식화 할 수있는 다양한 프랙탈이 있습니다. 이것은 상호 작용하는 두 개의 레이어가 필요하지만 각각은 그 자체로 흥미 롭습니다.

먼저 거북이가 필요합니다. 앞으로, 뒤로, 왼쪽, 오른쪽, 펜업, 펜 다운. L 시스템이 구동하지 않아도 거북이 형상을 사용하여 거북이 그래픽으로 만들 수있는 재미있는 모양이 많이 있습니다. "로고 그래픽"또는 "거북이 그래픽"을 검색합니다. 전체 로고 시스템은 실제로 괄호로 묶지 않은 Cambridge Polish 구문을 사용하는 Lisp 프로그래밍 환경 입니다. 그러나 거북이 개념을 사용하여 예쁜 그림을 얻기 위해 그렇게 멀리 갈 필요는 없습니다.

그런 다음 L 시스템을 실행하기위한 계층이 필요합니다. L- 시스템은 Post-systemsSemi-Thue 시스템관련이 있으며 virii와 마찬가지로 Turing Completeness의 경계에 걸쳐 있습니다. 개념은 문자열 재 작성 입니다. 매크로 확장 또는 재귀를 바인딩하는 추가 컨트롤이있는 프로 시저 집합으로 구현할 수 있습니다. 매크로 확장을 사용하는 경우 (아래 예에서와 같이), 기호를 거북이 명령에 매핑하는 프로 시저 세트와 인코딩 된 거북이 프로그램을 실행하기 위해 문자열 또는 배열을 반복하는 프로 시저가 필요합니다. 제한된 재귀 프로 시저 세트 ( :)의 경우 프로 시저 에 거북이 명령을 포함하고 각 프로 시저에 재귀 수준 검사를 추가하거나 처리기 함수에 인수 분해합니다.

다음은 매크로 확장과 매우 ​​축약 된 거북이 명령 세트를 사용하는 포스트 스크립트의 피타고라스 트리의 예입니다. python 및 mathematica의 몇 가지 예제는 my code golf challenge를 참조하십시오 .

ps l- 시스템 피타고라스 나무 luser-droog


Chaos and Fractals 라는 훌륭한 책이 있는데 , 각 장 끝에 프랙탈이나 다른 예제를 구현하는 간단한 예제 코드가 있습니다. 오래 전이 책을 읽었을 때 각 샘플 프로그램 (일부 기본 방언)을 웹 페이지에서 실행되는 Java 애플릿으로 변환했습니다. 애플릿은 여기에 있습니다 : http://hewgill.com/chaos-and-fractals/

샘플 중 하나는 간단한 Mandelbrot 구현입니다.


배울 수있는 또 다른 훌륭한 프랙탈은 Sierpinski Triangle Fractal입니다.

Basically, draw three corners of a triangle (an equilateral is preferred, but any triangle will work), then start a point P at one of those corners. Move P halfway to any of the 3 corners at random, and draw a point there. Again move P halfway towards any random corner, draw, and repeat.

You'd think the random motion would create a random result, but it really doesn't.

Reference: http://en.wikipedia.org/wiki/Sierpinski_triangle


The Sierpinski triangle and the Koch curve are special types of flame fractals. Flame fractals are a very generalized type of Iterated function system, since it uses non-linear functions.

An algorithm for IFS:es are as follows:

Start with a random point.

Repeat the following many times (a million at least, depending on final image size):

Apply one of N predefined transformations (matrix transformations or similar) to the point. An example would be that multiply each coordinate with 0.5. Plot the new point on the screen.

If the point is outside the screen, choose randomly a new one inside the screen instead.

If you want nice colors, let the color depend on the last used transformation.


I would start with something simple, like a Koch Snowflake. It's a simple process of taking a line and transforming it, then repeating the process recursively until it looks neat-o.

Something super simple like taking 2 points (a line) and adding a 3rd point (making a corner), then repeating on each new section that's created.

fractal(p0, p1){
    Pmid = midpoint(p0,p1) + moved some distance perpendicular to p0 or p1;
    fractal(p0,Pmid);
    fractal(Pmid, p1);
}

I think you might not see fractals as an algorithm or something to program. Fractals is a concept! It is a mathematical concept of detailed pattern repeating itself.

Therefore you can create a fractal in many ways, using different approaches, as shown in the image below.

여기에 이미지 설명 입력

Choose an approach and then investigate how to implement it. These four examples were implemented using Marvin Framework. The source codes are available here


The mandelbrot set is generated by repeatedly evaluating a function until it overflows (some defined limit), then checking how long it took you to overflow.

Pseudocode:

MAX_COUNT = 64 // if we haven't escaped to infinity after 64 iterations, 
               // then we're inside the mandelbrot set!!!

foreach (x-pixel)
  foreach (y-pixel)
    calculate x,y as mathematical coordinates from your pixel coordinates
    value = (x, y)
    count = 0
    while value.absolutevalue < 1 billion and count < MAX_COUNT
        value = value * value + (x, y)
        count = count + 1

    // the following should really be one statement, but I split it for clarity
    if count == MAX_COUNT 
        pixel_at (x-pixel, y-pixel) = BLACK
    else 
        pixel_at (x-pixel, y-pixel) = colors[count] // some color map. 

Notes:

value is a complex number. a complex number (a+bi) is squared to give (aa-b*b+2*abi). You'll have to use a complex type, or include that calculation in your loop.


Here's a simple and easy to understand code in Java for mandelbrot and other fractal examples

http://code.google.com/p/gaima/wiki/VLFImages

Just download the BuildFractal.jar to test it in Java and run with command:

java -Xmx1500M -jar BuildFractal.jar 1000 1000 default MANDELBROT

The source code is also free to download/explore/edit/expand.


Well, simple and graphically appealing don't really go hand in hand. If you're serious about programming fractals, I suggest reading up on iterated function systems and the advances that have been made in rendering them.

http://flam3.com/flame_draves.pdf


People above are using finding midpoints for sierpinski and Koch, I'd much more recommend copying shapes, scaling them, and then translating them to achieve the "fractal" effect. Pseudo-code in Java for sierpinski would look something like this:

public ShapeObject transform(ShapeObject originalCurve)
    {
        Make a copy of the original curve
        Scale x and y to half of the original
        make a copy of the copied shape, and translate it to the right so it touches the first copied shape
        make a third shape that is a copy of the first copy, and translate it halfway between the first and second shape,and translate it up
        Group the 3 new shapes into one
        return the new shape
    }

때로는 재미와 도전으로 프랙탈을 프로그래밍합니다. 여기에서 찾을 수 있습니다 . 코드는 P5.js 라이브러리를 사용하여 Javascript로 작성되며 HTML 소스 코드에서 직접 읽을 수 있습니다.

내가 본 알고리즘은 매우 간단합니다. 핵심 요소를 찾은 다음 반복해서 반복하면됩니다. 재귀 함수로 수행하지만 다르게 수행 할 수 있습니다.

참고 URL : https://stackoverflow.com/questions/425953/how-to-program-a-fractal

반응형