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

Complex Numbers ใน Java - การสร้างและคำนวณจำนวนเชิงซ้อน

Complex Numbers (จำนวนเชิงซ้อน) ประกอบด้วย 2 ส่วน: Real Part (ส่วนจริง) และ Imaginary Part (ส่วนจินตนาการ) เขียนในรูป a + bi โดยที่ i² = -1

Operations พื้นฐาน

OperationFormula
Addition(a + bi) + (c + di) = (a+c) + (b+d)i
Subtraction(a + bi) - (c + di) = (a-c) + (b-d)i
Multiplication(a + bi)(c + di) = (ac-bd) + (ad+bc)i
Division(a+bi)/(c+di) = [(ac+bd)/(c²+d²)] + [(bc-ad)/(c²+d²)]i
Conjugatea - bi
Magnitude|a+bi| = √(a²+b²)

ตัวอย่าง: Custom Complex Class

public final class Complex {
    private final double real;
    private final double imaginary;
    
    public Complex(double real, double imaginary) {
        this.real = real;
        this.imaginary = imaginary;
    }
    
    // Factory methods
    public static Complex of(double real, double imaginary) {
        return new Complex(real, imaginary);
    }
    
    public static Complex ofReal(double real) {
        return new Complex(real, 0);
    }
    
    // Getters
    public double getReal() { return real; }
    public double getImaginary() { return imaginary; }
    
    // Operations (Immutable - return new instance)
    public Complex add(Complex other) {
        return new Complex(this.real + other.real, this.imaginary + other.imaginary);
    }
    
    public Complex subtract(Complex other) {
        return new Complex(this.real - other.real, this.imaginary - other.imaginary);
    }
    
    public Complex multiply(Complex other) {
        double r = this.real * other.real - this.imaginary * other.imaginary;
        double i = this.real * other.imaginary + this.imaginary * other.real;
        return new Complex(r, i);
    }
    
    public Complex divide(Complex other) {
        double denominator = other.real * other.real + other.imaginary * other.imaginary;
        if (denominator == 0) {
            throw new ArithmeticException("Division by zero");
        }
        double r = (this.real * other.real + this.imaginary * other.imaginary) / denominator;
        double i = (this.imaginary * other.real - this.real * other.imaginary) / denominator;
        return new Complex(r, i);
    }
    
    public Complex conjugate() {
        return new Complex(real, -imaginary);
    }
    
    public double magnitude() {
        return Math.hypot(real, imaginary); // sqrt(real² + imag²)
    }
    
    public double phase() {
        return Math.atan2(imaginary, real); // Argument/angle
    }
    
    @Override
    public String toString() {
        if (imaginary >= 0) {
            return String.format("%.2f + %.2fi", real, imaginary);
        } else {
            return String.format("%.2f - %.2fi", real, -imaginary);
        }
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof Complex)) return false;
        Complex other = (Complex) obj;
        return Double.compare(real, other.real) == 0 
            && Double.compare(imaginary, other.imaginary) == 0;
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(real, imaginary);
    }
}

การใช้งาน

public class ComplexDemo {
    public static void main(String[] args) {
        Complex c1 = Complex.of(76.8, 24.0);
        Complex c2 = Complex.of(65.9, 11.23);
        
        System.out.println("c1 = " + c1);        // 76.80 + 24.00i
        System.out.println("c2 = " + c2);        // 65.90 + 11.23i
        System.out.println("c1 + c2 = " + c1.add(c2));       // 142.70 + 35.23i
        System.out.println("c1 - c2 = " + c1.subtract(c2));   // 10.90 + 12.77i
        System.out.println("c1 * c2 = " + c1.multiply(c2));   // 4792.08 + 2442.24i
        System.out.println("c1 / c2 = " + c1.divide(c2));     // 1.23 + 0.05i
        System.out.println("|c1| = " + c1.magnitude());       // 80.51
        System.out.println("conj(c1) = " + c1.conjugate());   // 76.80 - 24.00i
        System.out.println("phase(c1) = " + Math.toDegrees(c1.phase()) + "°"); // 17.35°
    }
}

Output

c1 = 76.80 + 24.00i
c2 = 65.90 + 11.23i
c1 + c2 = 142.70 + 35.23i
c1 - c2 = 10.90 + 12.77i
c1 * c2 = 4792.08 + 2442.24i
c1 / c2 = 1.23 + 0.05i
|c1| = 80.51
conj(c1) = 76.80 - 24.00i
phase(c1) = 17.35°

ใช้ Library: Apache Commons Math (แนะนำ Production)


    org.apache.commons
    commons-math3
    3.6.1


// Usage
import org.apache.commons.math3.complex.Complex;

Complex c1 = new Complex(76.8, 24.0);
Complex c2 = new Complex(65.9, 11.23);

Complex sum = c1.add(c2);
Complex product = c1.multiply(c2);
Complex exp = c1.exp();           // e^c1
Complex log = c1.log();           // ln(c1)
Complex sin = c1.sin();           // sin(c1)
Complex sqrt = c1.sqrt();         // √c1

Polar Coordinates (รูปแบบ極座標)

// สร้างจาก Magnitude และ Phase (Radians)
Complex polar = new Complex(Math.hypot(3, 4), Math.atan2(4, 3)); // 5∠53.13°

// หรือใช้ Factory (Commons Math)
Complex polar2 = Complex.fromPolar(5, Math.toRadians(53.13)); // magnitude, angle in radians

Use Cases

  • 📐 **Engineering/Physics**: AC Circuits, Signal Processing, Quantum Mechanics
  • 🎨 **Computer Graphics**: 2D Transformations, Rotations (Complex multiplication = Rotation + Scaling)
  • 📊 **Signal Processing**: FFT, Filters, Frequency Domain Analysis
  • 🔢 **Fractals**: Mandelbrot Set, Julia Sets
  • 🎵 **Audio Processing**: Phase manipulation, Modulation

Mandelbrot Set Example

public class Mandelbrot {
    public static int mandelbrot(Complex c, int maxIter) {
        Complex z = Complex.of(0, 0);
        for (int i = 0; i < maxIter; i++) {
            z = z.multiply(z).add(c); // z = z² + c
            if (z.magnitude() > 2) return i;
        }
        return maxIter;
    }
    
    public static void main(String[] args) {
        // Generate ASCII Mandelbrot
        for (double y = 1.2; y >= -1.2; y -= 0.05) {
            StringBuilder line = new StringBuilder();
            for (double x = -2.0; x <= 0.5; x += 0.03) {
                int iter = mandelbrot(Complex.of(x, y), 50);
                char ch = iter == 50 ? ' ' : " .:-=+*#%@" .charAt(iter % 10);
                line.append(ch);
            }
            System.out.println(line);
        }
    }
}