Microsoft MVP성태의 닷넷 이야기
.NET Framework: 588. C# - OxyPlot 라이브러리로 복소수 표현 [링크 복사], [링크+제목 복사],
조회: 16062
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 3개 있습니다.)

OxyPlot 라이브러리로 복소수 표현

요즘 "코딩 더 매트릭스" 책을 읽고 있습니다.

코딩 더 매트릭스 
; http://www.yes24.co.kr/24/goods/17967245

Coding the Matrix Resources
; http://resources.codingthematrix.com/

내부 코드가 파이썬으로 되어 있는데, 역시 쉽군요. ^^ 그래도 C#으로 실습해 보는 것도 재미있겠다 싶습니다.

가령, 2장 4절에 보면 "복소수 필드 C 다루기"가 나오는데요.

복소수의 경우 .NET 4.0부터 추가된 System.Numerics 어셈블리가 있어 별다른 어려움없이 사용할 수 있습니다. 게다가 자바와는 달리 연산자 재정의가 가능하므로 (파이썬만큼 편하지는 않지만) 직관적인 사칙 연산 표현도 가능합니다.

using System;
using System.Numerics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Complex n1 = new Complex(1, 3);
            Complex n2 = new Complex(10, 20);

            Console.WriteLine(n1 + n2); // 출력: (11, 23)

            Console.WriteLine(n1.Real);
            Console.WriteLine(n1.Imaginary);
        }
    }
}

복소수를 복소 평면에 시각화하는 도구로는 OxyPlot같은 라이브러리를 쓰면 됩니다.

C# Plotting 라이브러리 OxyPlot
; https://www.sysnet.pe.kr/2/0/10973

책에서 (별도 파일로 제공되는) plot 모듈은 복소수를 받아 내부적으로 SVG 파일로 변환을 하는데요. OxyPlot은 정해진 타입이 있으므로 그것으로 변환을 해주면 됩니다. 대충 다음과 같은 도우미 클래스를 하나 두고,

static class Helper
{
    public static void Add(this ScatterSeries scatter, Complex item)
    {
        scatter.Add(item.Real, item.Imaginary);
    }

    public static void Add(this ScatterSeries scatter, double real, double imagine)
    {
        scatter.Points.Add(new ScatterPoint(real, imagine));
    }

    public static void Add(this ScatterSeries scatter, IEnumerable<Complex> points)
    {
        if (points == null)
        {
            return;
        }

        foreach (Complex item in points)
        {
            scatter.Add(item);
        }
    }
}

이렇게 사용해 주면 됩니다.

protected override void OnLoad(EventArgs e)
{
    // ...[생략]...
    
    Complex[] S = new Complex[]
        {
            new Complex(2, 2),
            new Complex(3, 2),
            new Complex(1.75, 1),
            new Complex(2, 1),
            new Complex(2.25, 1),
            new Complex(2.5, 1),
            new Complex(2.75, 1),
            new Complex(3, 1),
            new Complex(3.25, 1),
        };

    ScatterSeries series = PlotsFromComplex(tS);
    _pm.Series.Add(series);

    // ...[생략]...
}

private ScatterSeries PlotsFromComplex(IEnumerable<Complex> complex)
{
    ScatterSeries series = new ScatterSeries();
    series.MarkerType = MarkerType.Circle;
    series.Add(complex);

    return series;
}

그럼, 책에서 나온 것과 같은 출력 화면을 볼 수 있습니다.

oxyplot_complex_1.png

복소수 덧셈으로 인한 평행 이동은 LINQ로 간단하게 표현이 가능합니다. 예를 들어, 위의 이미지에 출력된 S 목록에 (1, 2i) 만큼의 평행이동(translation)을 한다면 다음의 코드로 끝입니다.

Complex[] S = new Complex[]
    {
            // ...[생략]...
    };

Complex z = new Complex(1, 2);

var tS = from item in S
            select item + z;

물론, 스케일링(scaling)도 가능하고.

var tS = from item in S
         select item * (1.0 / 2); // 복소수의 실수/허수 좌표를 반으로 줄임

-1로 곱하면 180도 회전도 되고,

var tS = from item in S
         select item * -1;

i를 곱하면 90도 회전도 됩니다.

Complex z = new Complex(0, 1);
var tS = from item in S
         select item * z;

oxyplot_complex_2.png

이미지 데이터를 복소수화하는 것은 약간의 코드를 곁들이면 OK! ^^

var images = FromImage("img01.png");

private IEnumerable<Complex> FromImage(string filePath)
{
    List<Complex> list = new List<Complex>();

    using (Bitmap bitmap = Image.FromFile(filePath) as Bitmap)
    {
        for (int x = 0; x < bitmap.Width; x++)
        {
            for (int y = 0; y < bitmap.Height; y++)
            {
                Color color = bitmap.GetPixel(x, y);
                if (color.GetBrightness() < 0.5)
                {
                    Complex z = new Complex(x, -y + bitmap.Height);
                    list.Add(z);
                }
            }
        }
    }

    return list;
}

oxyplot_complex_3.png

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 5/21/2016]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... [46]  47  48  49  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12480정성태1/6/202112306.NET Framework: 999. C# - ArrayPool<T>와 MemoryPool<T> 소개파일 다운로드1
12479정성태1/6/20219724.NET Framework: 998. C# - OWIN 예제 프로젝트 만들기
12478정성태1/5/202111333.NET Framework: 997. C# - ArrayPool<T> 소개파일 다운로드1
12477정성태1/5/202113706기타: 79. github 코드 검색 방법 [1]
12476정성태1/5/202110388.NET Framework: 996. C# - 닷넷 코어에서 다른 스레드의 callstack을 구하는 방법파일 다운로드1
12475정성태1/5/202112974.NET Framework: 995. C# - Span<T>와 Memory<T> [1]파일 다운로드1
12474정성태1/4/202110482.NET Framework: 994. C# - (.NET Core 2.2부터 가능한) 프로세스 내부에서 CLR ETW 이벤트 수신 [1]파일 다운로드1
12473정성태1/4/20219282.NET Framework: 993. .NET 런타임에 따라 달라지는 정적 필드의 초기화 유무 [1]파일 다운로드1
12472정성태1/3/20219566디버깅 기술: 178. windbg - 디버그 시작 시 스크립트 실행
12471정성태1/1/202110039.NET Framework: 992. C# - .NET Core 3.0 이상부터 제공하는 runtimeOptions의 rollForward 옵션 [1]
12470정성태12/30/202010217.NET Framework: 991. .NET 5 응용 프로그램에서 WinRT API 호출 [1]파일 다운로드1
12469정성태12/30/202013800.NET Framework: 990. C# - SendInput Win32 API를 이용한 가상 키보드/마우스 [1]파일 다운로드1
12468정성태12/30/202010419Windows: 186. CMD Shell의 "Defaults"와 "Properties"에서 폰트 정보가 다른 문제 [1]
12467정성태12/29/202010369.NET Framework: 989. HttpContextAccessor를 통해 이해하는 AsyncLocal<T> [1]파일 다운로드1
12466정성태12/29/20208330.NET Framework: 988. C# - 지연 실행이 꼭 필요한 상황이 아니라면 singleton 패턴에서 DCLP보다는 static 초기화를 권장파일 다운로드1
12465정성태12/29/202011438.NET Framework: 987. .NET Profiler - FunctionID와 연관된 ClassID를 구할 수 없는 문제
12464정성태12/29/202010319.NET Framework: 986. pptfont.exe - PPT 파일에 숨겨진 폰트 설정을 일괄 삭제
12463정성태12/29/20209367개발 환경 구성: 520. RDP(mstsc.exe)의 다중 모니터 옵션 /multimon, /span
12462정성태12/27/202010982디버깅 기술: 177. windbg - (ASP.NET 환경에서 유용한) netext 확장
12461정성태12/21/202011807.NET Framework: 985. .NET 코드 리뷰 팁 [3]
12460정성태12/18/20209507기타: 78. 도서 소개 - C#으로 배우는 암호학
12459정성태12/16/20209889Linux: 35. C# - 리눅스 환경에서 클라이언트 소켓의 ephemeral port 재사용파일 다운로드1
12458정성태12/16/20209373오류 유형: 694. C# - Task.Start 메서드 호출 시 "System.InvalidOperationException: 'Start may not be called on a task that has completed.'" 예외 발생 [1]
12457정성태12/15/20208977Windows: 185. C# - Windows 10/2019부터 추가된 SIO_TCP_INFO파일 다운로드1
12456정성태12/15/20209253VS.NET IDE: 156. Visual Studio - "Migrate packages.config to PackageReference"
12455정성태12/15/20208752오류 유형: 693. DLL 로딩 시 0x800704ec - This Program is Blocked by Group Policy
... [46]  47  48  49  50  51  52  53  54  55  56  57  58  59  60  ...