I am new to Java and writing a class to represent Complex numbers.
//imports
public final class Complex extends Object implements Serializable{
private final double real;
private final double imaginary;
public Complex(final double real, final double imaginary){
this.real=real;
this.imaginary=imaginary;
}
//other constructors
//other methods
public Complex multiply(final Complex multiplicand){
return new Complex(this.real*multiplicand.real-this.imaginary*multiplicand.imaginary,this.real*multiplicand.imaginary+multiplicand.real*this.imaginary);
}
public Complex exponentiate(final Complex exponent){
return this.logarithm().multiply(exponent).exponentiate();
}
public Complex exponentiate(){
return new Complex(Math.exp(this.real)*Math.cos(this.imaginary),Math.exp(this.real)*Math.sin(this.imaginary));
}
public Complex logarithm(){
double realPart=Math.log(Math.sqrt(Math.pow(this.real,2)+Math.pow(this.imaginary,2)));
double imaginaryPart=Math.atan2(this.imaginary,this.real);
return new Complex(realPart,imaginaryPart);
}
public static final Complex I=new Complex(0.,1.);
public static final Complex E=new Complex(Math.E,0.);
public static final Complex PI=new Complex(Math.PI,0.);
}
This is how I attempted to implement (the principle value of) complex exponentiation using Java. However, the objects from the class use double to indicate their real and imaginary parts, and this leads to a serious imprecision.
For example, if I attempt System.out.println(Complex.E.exponentiate(Complex.PI.multiply(Complex.I)));
, an equivalent to e^(pi*i), the Euler's identity, the result will be -1.0+1.2246467991473532E-16i, but not simply -1.0, and this is due to the imprecision of floating-point variables.
I am wondering if there is any way to calculate a more precise value for exponential functions, either by improving my algorithm or taking an alternate approach to this. Thank you for reading my question.