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
1. Общие сведения
Учитель организовал несколько вопросов по Java-программированию в классе, это один из них
Разработайте класс Complex для инкапсуляции следующих операций над комплексными числами:
(1) конструктор с параметрами для инициализации множественных элементов
(2) Конструктор без параметров. Конструктор параметра генерации вызывается для завершения инициализации множественных членов.
(3) Статический метод и метод экземпляра, которые реализуют сложение, вычитание двух комплексных чисел.
(4) В сложной стандартной форме: x + iy выводит это комплексное число
(5) Напишите две функции для получения действительной части комплексного числа: getReal (), getImage () и мнимую часть.
Оригинальный вопрос учителя такой же, как и выше, и он сам добавил сложение, вычитание, умножение и деление двух комплексных чисел, используя метод примера. Если вы хотите написать статический метод, то есть метод класса, добавьте статический и измените его в соответствии с соответствующими изменениями. Разница в том, что методы экземпляра могут вызывать как переменные экземпляра и методы экземпляра, так и переменные класса и методы класса. Методы класса могут вызывать только переменные класса и методы класса. Из-за времени завтра уроки будут, поэтому я покажу пример.
3. Конкретный код и объяснение
package Four; /** * @author Kun Sun * @Date: 2013.10.15 */ import java.util.Scanner; открытый класс Complex/ множественный класс double real; // реальная часть double image; // мнимая часть Complex () / Конструктор без параметров Scanner input = new Scanner(System.in); double real = input.nextDouble(); double image = input.nextDouble(); Complex(real,image); > private void Complex (double real, double image)/ для конструкторов без аргументов // TODO Auto-generated method stub this.real = real; this.image = image; > Complex (double real, double image)/ конструктор с параметрами this.real = real; this.image = image; > public double getReal() < return real; >public void setReal(double real) < this.real = real; >public double getImage() < return image; >public void setImage(double image) < this.image = image; >Complex add (Комплекс а)/ Добавить комплексные числа double real2 = a.getReal(); double image2 = a.getImage(); double newReal = real + real2; double newImage = image + image2; Complex result = new Complex(newReal,newImage); return result; > Complex sub (Complex a)/ Вычитаем комплексные числа double real2 = a.getReal(); double image2 = a.getImage(); double newReal = real - real2; double newImage = image - image2; Complex result = new Complex(newReal,newImage); return result; > Complex mul (Complex a)/ умножить комплексные числа double real2 = a.getReal(); double image2 = a.getImage(); double newReal = real*real2 - image*image2; double newImage = image*real2 + real*image2; Complex result = new Complex(newReal,newImage); return result; > Complex div (Комплекс а)/ Делим комплексные числа double real2 = a.getReal(); double image2 = a.getImage(); double newReal = (real*real2 + image*image2)/(real2*real2 + image2*image2); double newImage = (image*real2 - real*image2)/(real2*real2 + image2*image2); Complex result = new Complex(newReal,newImage); return result; > public void print ()/ вывод if(image > 0)< System.out.println(real + " + " + image + "i"); >else if(image < 0)< System.out.println(real + "" + image + "i"); >else < System.out.println(real); >> >
package Four; /** * @author Kun Sun * @Date: 2013.10.15 */ public class MainClass/ для тестирования множественных классов /** * @param args */ public static void main(String[] args) < // TODO Auto-generated method stub System.out.println («Пожалуйста, попросите пользователя ввести действительные и мнимые части первого комплексного числа:»); Complex data1 = new Complex(); System.out.println («Пожалуйста, попросите пользователя ввести действительные и мнимые части второго комплексного числа:»); Complex data2 = new Complex(); // Ниже приведены сложение, вычитание, умножение и деление Complex result_add = data1.add(data2); Complex result_sub = data1.sub(data2); Complex result_mul = data1.mul(data2); Complex result_div = data1.div(data2); result_add.print(); result_sub.print(); result_mul.print(); result_div.print(); > >
4. Снимок экрана с результатами теста
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.