ComplexNumber.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package holeg.power_flow;
  2. public class ComplexNumber {
  3. public final double real;
  4. public final double imaginary;
  5. public final static ComplexNumber Zero = new ComplexNumber(0, 0);
  6. public final static ComplexNumber One = new ComplexNumber(1, 0);
  7. public final static ComplexNumber j = new ComplexNumber(0, -1);
  8. public ComplexNumber(double real) {
  9. this.real = real;
  10. this.imaginary = 0;
  11. }
  12. public ComplexNumber(double real, double imaginary) {
  13. this.real = real;
  14. this.imaginary = imaginary;
  15. }
  16. public static ComplexNumber fromPolar(double magnitude, double angle) {
  17. return new ComplexNumber(magnitude * Math.cos(angle), magnitude * Math.sin(angle));
  18. }
  19. public double lenSquared() {
  20. return real * real + imaginary * imaginary;
  21. }
  22. public double len() {
  23. return Math.sqrt(lenSquared());
  24. }
  25. public double angle() {
  26. return Math.atan2(imaginary, real);
  27. }
  28. public ComplexNumber add(ComplexNumber other) {
  29. return new ComplexNumber(real + other.real, imaginary + other.imaginary);
  30. }
  31. public ComplexNumber subtract(ComplexNumber other) {
  32. return new ComplexNumber(real - other.real, imaginary - other.imaginary);
  33. }
  34. public ComplexNumber multiply(double scalar) {
  35. return new ComplexNumber(real * scalar, imaginary * scalar);
  36. }
  37. public ComplexNumber multiply(ComplexNumber other) {
  38. return new ComplexNumber(real * other.real - imaginary * other.imaginary, imaginary * other.real + real * other.imaginary);
  39. }
  40. public ComplexNumber conjugate() {
  41. return new ComplexNumber(real, -imaginary);
  42. }
  43. public ComplexNumber reciprocal() {
  44. return new ComplexNumber(real / lenSquared(), -imaginary / lenSquared());
  45. }
  46. public ComplexNumber divide(ComplexNumber other) {
  47. return multiply(other.reciprocal());
  48. }
  49. public ComplexNumber negate() {
  50. return new ComplexNumber(-real, -imaginary);
  51. }
  52. public boolean isZero() {
  53. return Math.abs(real) < 0.0001 && Math.abs(imaginary) < 0.0001;
  54. }
  55. @Override
  56. public String toString() {
  57. if (imaginary >= 0)
  58. return String.format("%.4f + %.4fj", real, imaginary);
  59. return String.format("%.4f - %.4fj", real, Math.abs(imaginary));
  60. }
  61. }