12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- package holeg.power_flow;
- public class ComplexNumber {
- public final double real;
- public final double imaginary;
- public final static ComplexNumber Zero = new ComplexNumber(0, 0);
- public final static ComplexNumber One = new ComplexNumber(1, 0);
- public final static ComplexNumber j = new ComplexNumber(0, -1);
- public ComplexNumber(double real) {
- this.real = real;
- this.imaginary = 0;
- }
- public ComplexNumber(double real, double imaginary) {
- this.real = real;
- this.imaginary = imaginary;
- }
- public static ComplexNumber fromPolar(double magnitude, double angle) {
- return new ComplexNumber(magnitude * Math.cos(angle), magnitude * Math.sin(angle));
- }
- public double lenSquared() {
- return real * real + imaginary * imaginary;
- }
- public double len() {
- return Math.sqrt(lenSquared());
- }
- public double angle() {
- return Math.atan2(imaginary, real);
- }
- public ComplexNumber add(ComplexNumber other) {
- return new ComplexNumber(real + other.real, imaginary + other.imaginary);
- }
- public ComplexNumber subtract(ComplexNumber other) {
- return new ComplexNumber(real - other.real, imaginary - other.imaginary);
- }
- public ComplexNumber multiply(double scalar) {
- return new ComplexNumber(real * scalar, imaginary * scalar);
- }
- public ComplexNumber multiply(ComplexNumber other) {
- return new ComplexNumber(real * other.real - imaginary * other.imaginary, imaginary * other.real + real * other.imaginary);
- }
- public ComplexNumber conjugate() {
- return new ComplexNumber(real, -imaginary);
- }
- public ComplexNumber reciprocal() {
- return new ComplexNumber(real / lenSquared(), -imaginary / lenSquared());
- }
- public ComplexNumber divide(ComplexNumber other) {
- return multiply(other.reciprocal());
- }
- public ComplexNumber negate() {
- return new ComplexNumber(-real, -imaginary);
- }
- public boolean isZero() {
- return Math.abs(real) < 0.0001 && Math.abs(imaginary) < 0.0001;
- }
- @Override
- public String toString() {
- if (imaginary >= 0)
- return String.format("%.4f + %.4fj", real, imaginary);
- return String.format("%.4f - %.4fj", real, Math.abs(imaginary));
- }
- }
|