Question

I need the real and imaginary parts of the double for further processing and I have little to no idea how to convert them to a complex numbers. Any input would be dearly appreciated..

Was it helpful?

Solution

Java doesn't have a Complex number type.

To store/represent complex numbers you will either have to:

  • create your own type
  • use variables (i.e. Re, Im)
  • or use 3rd party library

Also, as far as "converting" a double to a Complex number, a double can obviously only represent either the imaginary or the real part of a complex number. So you will have to be more specific about what you mean. If you want to convert a double to a complex number of real part equal to your double and imaginary part equal to 0. Then that should be pretty straight forward..

If you'd like to create your own type it might look like this:

class ComplexNumber{
   public ComplexNumber(double re, double im)
   {
       _re = re;
       _im = im;
   }

   private double _re;
   public double getReal(){
      return _re;
   }
   private double _im;
   public double getImaginary(){
       return _im;
   }

   @overrides
   public boolean equals(object other){
       if(other == null)
          return false;
       ComplexNumber n = (ComplexNumber)other;
       return _re.equals(n._re) && _im.equals(n._im);
   }

   @overrides
   public boolean getHashCode(){
       return _re.getHashCode() ^ _im.getHashCode();
   }

   @overrides
   public void toString(){
       return "(" + re.toString() + "," + im.toString() + ")";
   }
}

Notice that this class has immutable semantics (i.e. you cannot modify it's internal state once it has been instantiated). This is desirable if you're going to represent a complex number. Then you can static methods to add/subtract/multipy/divide these complex numbers.

OTHER TIPS

I would recommend you build a complex number class, as you are probably aware you can represent complex numbers on a plane using two coordinate values, so the class could hold two doubles for these. Then just look up how to divide, multiply, subtract and add complex numbers, and make methods divide, multiply, subtract, add, each of which would take a complex number object as a parameter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top