Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- public class Complex {
- public Complex()
- {
- }
- public Complex(double real , double imaginary)
- {
- this.real = real;
- this.imaginary = imaginary;
- }
- public static Complex sum(Complex left, Complex right)
- {
- return new Complex(left.getReal()+right.getReal(),left.getImaginary()+right.getImaginary());
- }
- public static Complex mmultiply(Complex left, Complex right)
- {
- return new Complex(left.getReal()*right.getReal() - left.getImaginary()*right.getImaginary(),
- left.getImaginary()*right.getReal()+ left.getReal()*right.getImaginary());
- }
- public static Complex division (Complex left, Complex right)
- {
- if (right.magnitude() == 0) throw new IllegalArgumentException("Division by zero!");
- return new Complex((left.getReal()*right.getReal() + left.getImaginary()*right.getImaginary())/(right.getReal() *right.getReal()),
- (left.getImaginary()*right.getReal()+ left.getReal()*right.getImaginary())/(right.getReal() *right.getReal())) ;
- }
- public static Complex pow(Complex val, double degree)
- {
- double tempReal = val.getReal() == 0 ? 0 : Math.pow(val.magnitude(),degree) * Math.cos(degree * val.phase());
- double tempImaginary = val.getImaginary() == 0 ? 0 : Math.pow(val.magnitude(),degree) * Math.sin(degree * val.phase());
- return new Complex(tempReal,tempImaginary);
- }
- public static Complex sqrt(Complex val)
- {
- return Complex.fromPolarCoordinates(Math.sqrt(val.magnitude()),val.phase()/2);
- }
- public double magnitude()
- {
- if (real > 0) return Math.sqrt(real*real+imaginary*imaginary);
- if (real < 0 && imaginary >= 0) return Math.PI + Math.sqrt(real*real+imaginary*imaginary);
- if ( real < 0 && imaginary < 0) return -Math.PI + Math.sqrt(real*real+imaginary*imaginary);
- if(real == 0 && imaginary >0) return Math.PI/2;
- if(real == 0 && imaginary <0) return -Math.PI/2;
- return 0;
- }
- public double phase()
- {
- return Math.atan2(imaginary,real);
- }
- public static Complex fromPolarCoordinates(double magnitude, double phase)
- {
- double tempReal = magnitude * Math.cos(phase);
- double temoImaginary = magnitude * Math.sin(phase);
- return new Complex(tempReal,temoImaginary);
- }
- @Override
- public String toString() {
- final StringBuffer sb = new StringBuffer("Complex{");
- sb.append("real=").append(real);
- sb.append(", imaginary=").append(imaginary);
- sb.append('}');
- return sb.toString();
- }
- public double getImaginary() {
- return imaginary;
- }
- public void setImaginary(double imaginary) {
- this.imaginary = imaginary;
- }
- public double getReal() {
- return real;
- }
- public void setReal(double real) {
- this.real = real;
- }
- private double real = 0;
- private double imaginary = 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement