package com.njcn.advance.event.cause.model;

/**
 * 复数结构
 * 对应C语言中的complex结构体
 */
public class Complex {
    private double real;  // 实部
    private double imag;  // 虚部

    public Complex() {
        this(0.0, 0.0);
    }

    public Complex(double real, double imag) {
        this.real = real;
        this.imag = imag;
    }

    // 复数加法
    public Complex plus(Complex other) {
        return new Complex(this.real + other.real, this.imag + other.imag);
    }

    // 复数减法
    public Complex minus(Complex other) {
        return new Complex(this.real - other.real, this.imag - other.imag);
    }

    // 复数乘法
    public Complex multiply(Complex other) {
        double newReal = this.real * other.real - this.imag * other.imag;
        double newImag = this.real * other.imag + this.imag * other.real;
        return new Complex(newReal, newImag);
    }

    // 复数除法
    public Complex divide(Complex other) {
        double denominator = other.real * other.real + other.imag * other.imag;
        if (Math.abs(denominator) < 1e-10) {
            throw new ArithmeticException("Division by zero complex number");
        }
        double newReal = (this.real * other.real + this.imag * other.imag) / denominator;
        double newImag = (this.imag * other.real - this.real * other.imag) / denominator;
        return new Complex(newReal, newImag);
    }

    // 复数模
    public double abs() {
        return Math.sqrt(real * real + imag * imag);
    }

    // 复数共轭
    public Complex conjugate() {
        return new Complex(real, -imag);
    }

    // 复数幅角
    public double phase() {
        return Math.atan2(imag, real);
    }

    // Getters and Setters
    public double getReal() {
        return real;
    }

    public void setReal(double real) {
        this.real = real;
    }

    public double getImag() {
        return imag;
    }

    public void setImag(double imag) {
        this.imag = imag;
    }

    @Override
    public String toString() {
        if (imag >= 0) {
            return String.format("%.6f + %.6fi", real, imag);
        } else {
            return String.format("%.6f - %.6fi", real, -imag);
        }
    }
}