Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Complex Numbers (จำนวน مختلط) ใน C#

จำนวน مختلط (Complex Number) ประกอบด้วยส่วนจริง (Real Part) และส่วนจินตภาพ (Imaginary Part) รูปแบบ a + bi โดย i = √-1 ใน C# สามารถสร้าง Struct เอง หรือใช้ System.Numerics.Complex (แนะนำ)

ใช้ System.Numerics.Complex (Built-in, .NET 4.0+)

using System;
using System.Numerics;

class Demo
{
    static void Main()
    {
        Complex c1 = new Complex(7, 5);  // 7 + 5i
        Complex c2 = new Complex(2, 3);  // 2 + 3i
        
        // Arithmetic Operations
        Complex sum = c1 + c2;        // (9 + 8i)
        Complex diff = c1 - c2;       // (5 + 2i)
        Complex prod = c1 * c2;       // (-1 + 31i)
        Complex quot = c1 / c2;       // (~2.15 + 0.23i)
        
        // Properties
        double magnitude = c1.Magnitude;      // √(7²+5²) = √74 ≈ 8.6
        double phase = c1.Phase;              // Radians
        
        Console.WriteLine($"c1 = {c1}");
        Console.WriteLine($"c2 = {c2}");
        Console.WriteLine($"Sum = {sum}");
        Console.WriteLine($"Magnitude = {magnitude}");
        Console.WriteLine($"Phase = {phase} radians");
    }
}

สร้าง Struct เอง (Custom Implementation)

using System;

public struct Complex
{
    public int Real;
    public int Imaginary;
    
    public Complex(int real, int imaginary)
    {
        Real = real;
        Imaginary = imaginary;
    }
    
    // Operator Overloading สำหรับ +
    public static Complex operator +(Complex one, Complex two)
    {
        return new Complex(one.Real + two.Real, one.Imaginary + two.Imaginary);
    }
    
    public override string ToString()
    {
        return $"{Real} + {Imaginary}i";
    }
}

class Demo
{
    static void Main()
    {
        Complex val1 = new Complex(7, 1);
        Complex val2 = new Complex(2, 6);
        Complex res = val1 + val2;
        
        Console.WriteLine($"First: {val1}");      // 7 + 1i
        Console.WriteLine($"Second: {val2}");     // 2 + 6i
        Console.WriteLine($"Result (Sum): {res}"); // 9 + 7i
    }
}

ผลลัพธ์

First: 7 + 1i
Second: 2 + 6i
Result (Sum): 9 + 7i

คุณสมบัติของ System.Numerics.Complex

  • Real, Imaginary - ส่วนจริง/จินตภาพ
  • Magnitude - ขนาด (Modulus) = √(Real² + Imaginary²)
  • Phase - มุม (Argument) ใน Radians
  • Conjugate - Conjugate (a - bi)
  • Reciprocal - 1/(a+bi)
  • Operator Overloads: +, -, *, /, ==, !=
  • Static Methods: Log, Exp, Sqrt, Pow, Sin, Cos, Tan etc.

ต้องเพิ่ม Reference: System.Numerics.dll หรือ <PackageReference Include="System.Numerics.Vectors" />