Microsoft MVP성태의 닷넷 이야기
Math: 17. C# - 복소수 타입의 승수를 지원하는 Power 메서드 [링크 복사], [링크+제목 복사],
조회: 15364
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C# - 복소수 타입의 승수를 지원하는 Power 메서드

Math.PI를 오일러 공식에 대입하면 다음의 식을 얻게 됩니다.

eπi + 1 = 0;

그런데, 저 값을 실제로 코드로 구현하려면 어떻게 해야 할까요? 직관적인 코드로는 다음과 같이 작성해야 하는데,

Complex i = new Complex(0, 1);

double negOne = Math.Pow(Math.E, (Math.PI * i)); // 컴파일 에러!

애석하게도 닷넷 BCL에 기본 제공되는 Math.Pow 메서드는 복소수 타입의 제곱을 지원하지 않기 때문에 컴파일 오류가 발생합니다.

다행히 검색해 보면, Math.NET 라이브러리에 구현된 Complex32 타입은 복소수 타입의 제곱 함수를 제공해 줍니다.

Math.NET Numerics 3.11.1 
; https://www.nuget.org/packages/MathNet.Numerics/

Math.NET은 Nuget으로도 제공하기 때문에 다음과 같이 참조 추가를 해주고,

Install-Package MathNet.Numerics 

Complex32 타입에서 제공하는 Power 메서드를 사용해 복소수 승수를 사용해 주면 됩니다. 이렇게!

Complex32 i = new Complex32(0, 1);
Complex32 e = new Complex32((float)Math.E, 0);
Complex32 pi = new Complex32((float)Math.PI, 0);

Complex32 negOne = e.Power(pi * i);

Console.WriteLine(negOne); // (-1, 1.509958E-07)




Complex32 타입의 소스 코드를 참조하면 당연히 System.Nuemrics의 Complex 타입에도 복소수를 받는 Pow 메서드를 구현하는 것이 가능합니다. 이를 위해 다음과 같은 도우미 함수를 Math.NET으로부터 복사해 가져오고,

static class Helper
{
    public static readonly Complex Zero = new Complex(0, 0);
    public static readonly Complex One = new Complex(1, 0);
    public static readonly Complex NaN = new Complex(double.NaN, double.NaN);

    public static bool IsReal(this Complex complex)
    {
        return (complex.Imaginary == 0.0);
    }

    public static bool IsZero(this Complex complex)
    {
        return ((complex.Real == 0.0) && (complex.Imaginary == 0.0));
    }

    public static bool IsRealNonNegative(this Complex complex)
    {
        return ((complex.Imaginary == 0.0) && (complex.Real >= 0.0));
    }

    public static Complex Power(this Complex src, Complex exponent)
    {
        if (src.IsZero())
        {
            if (exponent.IsZero())
            {
                return One;
            }

            if (exponent.Real > 0f)
            {
                return Zero;
            }

            if (exponent.Real >= 0f)
            {
                return NaN;
            }

            if (exponent.Imaginary != 0f)
            {
                return new Complex(double.PositiveInfinity, double.PositiveInfinity);
            }

            return new Complex(double.PositiveInfinity, 0f);
        }

        Complex complex = exponent * src.NaturalLogarithm();
        return complex.Exponential();
    }

    public static Complex NaturalLogarithm(this Complex src)
    {
        if (src.IsRealNonNegative())
        {
            return new Complex(Math.Log(src.Real), 0);
        }

        return new Complex(0.5 * (Math.Log(src.MagnitudeSquared())), src.Phase());
    }

    public static double MagnitudeSquared(this Complex src)
    {
        return ((src.Real * src.Real) + (src.Imaginary * src.Imaginary));
    }

    public static double Phase(this Complex src)
    {
        if ((src.Imaginary == 0f) && (src.Real < 0f))
        {
            return Math.PI;
        }

        return Math.Atan2(src.Imaginary, src.Real);
    }

    public static Complex Exponential(this Complex src)
    {
        double real = Math.Exp(src.Real);

        if (src.IsReal())
        {
            return new Complex(real, 0f);
        }

        return new Complex(real * (Math.Cos(src.Imaginary)),
                            real * (Math.Sin(src.Imaginary)));
    }
}

System.Numerics.Complex 타입을 이용해 Math.Pow 기능을 다음과 같이 구현할 수 있습니다.

Complex i = new Complex(0, 1);
Complex e = new Complex(Math.E, 0);

Complex negOne = e.Power(Math.PI * i);

Console.WriteLine(negOne); // (-1, 1.22460635382238E-16)

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




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

[연관 글]






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

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

비밀번호

댓글 작성자
 




... 61  62  63  64  65  66  67  [68]  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
11940정성태6/13/201910836개발 환경 구성: 443. Visual Studio의 Connection Manager 기능(Remote SSH 관리)을 위한 명령행 도구파일 다운로드1
11939정성태6/13/20199903오류 유형: 545. Managed Debugging Assistant 'FatalExecutionEngineError'
11938정성태6/12/201911563Math: 59. C# - 웨이트 벡터 갱신식을 이용한 퍼셉트론 분류파일 다운로드1
11937정성태6/11/201918016개발 환경 구성: 442. .NET Core 3.0 preview 5를 이용해 Windows Forms/WPF 응용 프로그램 개발 [1]
11936정성태6/10/201911270Math: 58. C# - 최소 자승법의 1차, 2차 수렴 그래프 변화 확인 [2]파일 다운로드1
11935정성태6/9/201911955.NET Framework: 843. C# - PLplot 출력을 파일이 아닌 Window 화면으로 변경
11934정성태6/7/201913144VC++: 133. typedef struct와 타입 전방 선언으로 인한 C2371 오류파일 다운로드1
11933정성태6/7/201913190VC++: 132. enum 정의를 C++11의 enum class로 바꿀 때 유의할 사항파일 다운로드1
11932정성태6/7/201911732오류 유형: 544. C++ - fatal error C1017: invalid integer constant expression파일 다운로드1
11931정성태6/6/201911856개발 환경 구성: 441. C# - CairoSharp/GtkSharp 사용을 위한 프로젝트 구성 방법
11930정성태6/5/201912406.NET Framework: 842. .NET Reflection을 대체할 System.Reflection.Metadata 소개 [1]
11929정성태6/5/201912148.NET Framework: 841. Windows Forms/C# - 클립보드에 RTF 텍스트를 복사 및 확인하는 방법 [1]
11928정성태6/5/201910774오류 유형: 543. PowerShell 확장 설치 시 "Catalog file '[...].cat' is not found in the contents of the module" 오류 발생
11927정성태6/5/201911768스크립트: 15. PowerShell ISE의 스크립트를 복사 후 PPT/Word에 붙여 넣으면 한글이 깨지는 문제 [1]
11926정성태6/4/201913204오류 유형: 542. Visual Studio - pointer to incomplete class type is not allowed
11925정성태6/4/201912013VC++: 131. Visual C++ - uuid 확장 속성과 __uuidof 확장 연산자파일 다운로드1
11924정성태5/30/201913765Math: 57. C# - 해석학적 방법을 이용한 최소 자승법 [1]파일 다운로드1
11923정성태5/30/201913406Math: 56. C# - 그래프 그리기로 알아보는 경사 하강법의 최소/최댓값 구하기파일 다운로드1
11922정성태5/29/201911470.NET Framework: 840. ML.NET 데이터 정규화파일 다운로드1
11921정성태5/28/201916409Math: 55. C# - 다항식을 위한 최소 자승법(Least Squares Method)파일 다운로드1
11920정성태5/28/201910031.NET Framework: 839. C# - PLplot 색상 제어
11919정성태5/27/201913127Math: 54. C# - 최소 자승법의 1차 함수에 대한 매개변수를 단순 for 문으로 구하는 방법 [1]파일 다운로드1
11918정성태5/25/201914334Math: 53. C# - 행렬식을 이용한 최소 자승법(LSM: Least Square Method)파일 다운로드1
11917정성태5/24/201914441Math: 52. MathNet을 이용한 간단한 통계 정보 처리 - 분산/표준편차파일 다운로드1
11916정성태5/24/201912449Math: 51. MathNET + OxyPlot을 이용한 간단한 통계 정보 처리 - Histogram파일 다운로드1
11915정성태5/24/201914741Linux: 11. 리눅스의 환경 변수 관련 함수 정리 - putenv, setenv, unsetenv
... 61  62  63  64  65  66  67  [68]  69  70  71  72  73  74  75  ...