Complex.java
Below is the syntax highlighted version of Complex.java from §3.2 Creating Data Types.
/****************************************************************************** * Compilation: javac Complex.java * Execution: java Complex * * Data type for complex numbers. * * The data type is "immutable" so once you create and initialize * a Complex object, you cannot change it. The "final" keyword * when declaring re and im enforces this rule, making it a * compile-time error to change the .re or .im instance variables after * they've been initialized. * * % java Complex * a = 5.0 + 6.0i * b = -3.0 + 4.0i * Re(a) = 5.0 * Im(a) = 6.0 * b + a = 2.0 + 10.0i * a - b = 8.0 + 2.0i * a * b = -39.0 + 2.0i * b * a = -39.0 + 2.0i * a / b = 0.36 - 1.52i * (a / b) * b = 5.0 + 6.0i * conj(a) = 5.0 - 6.0i * |a| = 7.810249675906654 * tan(a) = -6.685231390246571E-6 + 1.0000103108981198i * ******************************************************************************/ import java.util.Objects; public class Complex private final double re; // the real part private final double im; // the imaginary part // create a new object with the given real and imaginary parts public Complex(double real, double imag) re = real; im = imag; > // return a string representation of the invoking Complex object public String toString() if (im == 0) return re + ""; if (re == 0) return im + "i"; if (im 0) return re + " - " + (-im) + "i"; return re + " + " + im + "i"; > // return abs/modulus/magnitude public double abs() return Math.hypot(re, im); > // return angle/phase/argument, normalized to be between -pi and pi public double phase() return Math.atan2(im, re); > // return a new Complex object whose value is (this + b) public Complex plus(Complex b) Complex a = this; // invoking object double real = a.re + b.re; double imag = a.im + b.im; return new Complex(real, imag); > // return a new Complex object whose value is (this - b) public Complex minus(Complex b) Complex a = this; double real = a.re - b.re; double imag = a.im - b.im; return new Complex(real, imag); > // return a new Complex object whose value is (this * b) public Complex times(Complex b) Complex a = this; double real = a.re * b.re - a.im * b.im; double imag = a.re * b.im + a.im * b.re; return new Complex(real, imag); > // return a new object whose value is (this * alpha) public Complex scale(double alpha) return new Complex(alpha * re, alpha * im); > // return a new Complex object whose value is the conjugate of this public Complex conjugate() return new Complex(re, -im); > // return a new Complex object whose value is the reciprocal of this public Complex reciprocal() double scale = re*re + im*im; return new Complex(re / scale, -im / scale); > // return the real or imaginary part public double re() return re; > public double im() return im; > // return a / b public Complex divides(Complex b) Complex a = this; return a.times(b.reciprocal()); > // return a new Complex object whose value is the complex exponential of this public Complex exp() return new Complex(Math.exp(re) * Math.cos(im), Math.exp(re) * Math.sin(im)); > // return a new Complex object whose value is the complex sine of this public Complex sin() return new Complex(Math.sin(re) * Math.cosh(im), Math.cos(re) * Math.sinh(im)); > // return a new Complex object whose value is the complex cosine of this public Complex cos() return new Complex(Math.cos(re) * Math.cosh(im), -Math.sin(re) * Math.sinh(im)); > // return a new Complex object whose value is the complex tangent of this public Complex tan() return sin().divides(cos()); > // a static version of plus public static Complex plus(Complex a, Complex b) double real = a.re + b.re; double imag = a.im + b.im; Complex sum = new Complex(real, imag); return sum; > // See Section 3.3. public boolean equals(Object x) if (x == null) return false; if (this.getClass() != x.getClass()) return false; Complex that = (Complex) x; return (this.re == that.re) && (this.im == that.im); > // See Section 3.3. public int hashCode() return Objects.hash(re, im); > // sample client for testing public static void main(String[] args) Complex a = new Complex(5.0, 6.0); Complex b = new Complex(-3.0, 4.0); StdOut.println("a normal"> + a); StdOut.println("b normal"> + b); StdOut.println("Re(a) normal"> + a.re()); StdOut.println("Im(a) normal"> + a.im()); StdOut.println("b + a normal"> + b.plus(a)); StdOut.println("a - b normal"> + a.minus(b)); StdOut.println("a * b normal"> + a.times(b)); StdOut.println("b * a normal"> + b.times(a)); StdOut.println("a / b normal"> + a.divides(b)); StdOut.println("(a / b) * b normal"> + a.divides(b).times(b)); StdOut.println("conj(a) normal"> + a.conjugate()); StdOut.println("|a| normal"> + a.abs()); StdOut.println("tan(a) normal"> + a.tan()); > >
Иллюстрированный самоучитель по Java
Комплексные числа широко используются не только в математике. Они часто применяются в графических преобразованиях, в построении фракталов, не говоря уже о физике и технических дисциплинах. Но класс, описывающий комплексные числа, почему-то не включен в стандартную библиотеку Java. Восполним этот пробел.
Листинг 2.4 длинный, но просмотрите его внимательно, при обучении языку программирования очень полезно чтение программ на этом языке. Более того, только программы и стоит читать, пояснения автора лишь мешают вникнуть в смысл действий (шутка).
Листинг 2.4. Класс Complex.
class Complex < private static final double EPS = le-12; // Точность вычислений private double re, im; // Действительная и мнимая часть // Четыре конструктора Complex(double re, double im) < this, re = re; this.im = im; >Complex(double re)
Complex Numbers in Java
Complex numbers are those that have an imaginary part and a real part associated with it. They can be added and subtracted like regular numbers. The real parts and imaginary parts are respectively added or subtracted or even multiplied and divided.
Example
public class Demo < double my_real; double my_imag; public Demo(double my_real, double my_imag)< this.my_real = my_real; this.my_imag = my_imag; >public static void main(String[] args) < Demo n1 = new Demo(76.8, 24.0), n2 = new Demo(65.9, 11.23), temp; temp = add(n1, n2); System.out.printf("The sum of two complex numbers is %.1f + %.1fi", temp.my_real, temp.my_imag); >public static Demo add(Demo n1, Demo n2) < Demo temp = new Demo(0.0, 0.0); temp.my_real = n1.my_real + n2.my_real; temp.my_imag = n1.my_imag + n2.my_imag; return(temp); >>
Output
The sum of two complex numbers is 142.7 + 35.2i
A class named Demo defines two double valued numbers, my_real, and my_imag. A constructor is defined, that takes these two values. In the main function, an instance of the Demo class is created, and the elements are added using the ‘add’ function and assigned to a temporary object (it is created in the main function).
Next, they are displayed on the console. In the main function, another temporary instance is created, and the real parts and imaginary parts of the complex numbers are added respectively, and this temporary object is returned as output.
Коплексные числа Java
Начался новый учебный год, начали учить Java, и нас сразу закинули на ООП, не объяснив основ.
Мне необходима помощь c одним заданием.
Задание:
«Создать класс Complex, описывающий комплексное число и хранящий действительную и мнимую части в виде вещественных чисел. Реализовать конструкторы, необходимые для удобной работы с классом :
1. конструктор без параметров: действительная и мнимая части равны нулю;
2. конструктор, принимающий одно число в качестве параметра: действительную часть. Мнимая часть равна нулю;
3. конструктор, принимающий два числа в качестве параметра: действительную и мнимую части;
4. конструктор, принимающий ссылку на класс «комплексное число» в качестве параметра и устанавливающий действительную и мнимую части текущего объекта равными действительной и мнимой частям объекта, полученного в качестве параметра.
Написать по два метода для каждой операции: сложения, вычитания, умножения, сравнения.
В качестве примера рассмотрим операцию сложения.
Один метод должен складывать содержимое текущего объекта с содержимым объекта, переданного в качестве параметра:
public void plus(Complex other) re += other.re;
im+= other.im;
>
Здесь: Complex – имя класса, описывающего комплексное число, re – действительная часть, im – мнимая часть.
Другой метод – статический – должен складывать два «внешних» комплексных числа, переданных в качестве параметров:
public static Complex plus( Complex c1, Complex c2) //используем конструктор №3:
return new Complex( c1.re+c2.re, c1.im+c2.im);
>»
Первые три конструктора написал, а вот с 4м проблема.
С первым методом и примера я тоже разобрался,
а второй для меня не ясен.
Вот мой код:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
package lab1; public class Complex { public double re; public double im; public void plus(Complex other){ this.re += other.re; this.im += other.im; } public static Complex plus( Complex c1, Complex c2){ return new Complex(c1.re+c2.re, c1.im+c2.im); } public void minus(Complex other){ this.re -= other.re; this.im -= other.im; } public static Complex minus( Complex c1, Complex c2){ return new Complex(c1.re-c2.re, c1.im-c2.im); } public void mult(Complex other){ re *= other.re; im *= other.im; } public static Complex mult( Complex c1, Complex c2){ return new Complex(c1.re*c2.re, c1.im*c2.im); } public void X(double x){ this.re *= x; this.im *= x; } public void print(){ if(this.im 0){ System.out.println(this.re+" - "+Math.abs(this.im)+"i"); } if(this.im >0){ System.out.println(this.re+" + "+this.im+"i"); } } public Complex() { this.re += 0; this.im += 0; } public Complex(double re) { this.re += re; this.im += 0; } public Complex(double re, double im) { this.re += re; this.im += im; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
package lab1; public class Lab1 { public static void main(String[] args) { Complex z1 = new Complex(3, -1); Complex z2 = new Complex(-2, 3); z1.plus(z2); z1.print(); z1.X(5); z1.print(); } }