Complex

  • 数学计算:加减乘除、求模、辐角、平方根、倒数、相反数、共轭复数等
  • 其他:字符串转复数parseComplex()、复数转字符串toString()
import java.util.regex.Matcher;
import java.util.regex.Pattern;/*** A complex value with double precision.** @author Cloudy1225*/
public class Complex {private double real, imag;/***** Constant Variables *****/public static final Complex REAL_UNIT = new Complex(1.0, 0.0);public static final Complex NEG_REAL_UNIT = new Complex(-1.0, 0.0);public static final Complex IMAG_UNIT = new Complex(0.0, 1.0);public static final Complex NEG_IMAG_UNIT = new Complex(0.0, -1.0);public static final Complex ZERO = new Complex(0.0);/***** Constructors *****/public Complex(double real, double imag) {this.real = real;this.imag = imag;}public Complex(double real) {this.real = real;this.imag = 0;}public Complex() {this.real = 0;this.imag = 0;}/***** getter and setter *****/public double real() {return this.real;}public double imag() {return this.imag;}protected void set(double real, double imag) {this.real = real;this.imag = imag;}protected void setReal(double real) {this.real = real;}protected void setImag(double imag) {this.imag = imag;}/***** Override some methods in Object *****/@Overridepublic String toString() {if (this.imag > 0) {return ((real==0) ? "" : real+"+") + imag + "i";} else if (this.imag < 0) {return ((real==0) ? "" : real+"") + imag + "i";} else {return String.valueOf(real);}}@Overridepublic boolean equals(Object obj) {if (!(obj instanceof Complex)) return false;Complex other = (Complex) obj;return this.real == other.real && this.imag == other.imag;}@Overridepublic int hashCode() {return Double.valueOf(this.real).hashCode() ^ Double.valueOf(this.imag).hashCode();}/*** Create a deep copy of the complex** @return deep copy of the complex*/public Complex copy() {return new Complex(this.real, this.imag);}/*** Constructs a newly allocated Complex object that* represents the complex value represented by the double.** @param  d  a double to be converted to a complex.*/public static Complex valueOf(double d) {return new Complex(d);}/*** Constructs a newly allocated Complex object that* represents the complex value represented by the string.** @param  s  a string to be converted to a complex.* @throws    NumberFormatException  if the string does not contain a*            parsable number.*/public static Complex valueOf(String s) {return parseComplex(s);}/*** Constructs a newly allocated Complex object that* represents the complex value represented by the string.** @param  s  a string to be converted to a complex.* @throws    NumberFormatException  if the string does not contain a*            parsable number.*/public static Complex parseComplex(String s) {double real = 0;double imag = 0;final String doubleRegex = "[-+]?(\\d+(\\.\\d*)?|\\.\\d+)([eE]([-+]?([012]?\\d{1,2}|30[0-7])|-3([01]?[4-9]|[012]?[0-3])))?";final String pureImagRegex = doubleRegex+"[a-zA-Z]";final String complexRegex1 = "(?<real>"+doubleRegex+")" + "(?<imag>"+doubleRegex+")" + "[a-zA-Z]";final String complexRegex2 = "(?<imag>"+doubleRegex+")" + "[a-zA-Z]" + "(?<real>"+doubleRegex+")";if (Pattern.compile(doubleRegex).matcher(s).matches()) { // It's just a real number.real = Double.parseDouble(s);} else if (Pattern.compile(pureImagRegex).matcher(s).matches()) { // It's just a pure imaginary number.imag = Double.parseDouble(s.substring(0, s.length()-1));} else {Matcher matcher = Pattern.compile(complexRegex1).matcher(s);if (matcher.matches()) { // It's like '20.02+12.25i'.real = Double.parseDouble(matcher.group("real"));imag = Double.parseDouble(matcher.group("imag"));} else {matcher = Pattern.compile(complexRegex2).matcher(s);if(matcher.matches()) { // It's like '12.25i+20.02'.real = Double.parseDouble(matcher.group("real"));imag = Double.parseDouble(matcher.group("imag"));} else {throw new NumberFormatException("\""+ s + "\" can't be translated as a complex.");}}}return new Complex(real, imag);}/***** Arithmetic Operations *****//*** Does this equal another complex within the allowed error range 1e-6?** @param complex complex to be compared with* @return true / false*/public boolean eq(Complex complex) {return Math.abs(real-complex.real)+Math.abs(imag-complex.imag) < 1e-6;}/*** Returns a new Complex whose value is {this + augend}** @param augend complex to be added to this* @return {this + augend}*/public Complex add(Complex augend) {return new Complex(this.real+augend.real, this.imag+augend.imag);}/*** Returns a new Complex whose value is {this + real}** @param real real number to be added to this* @return {this + real}*/public Complex add(double real) {return new Complex(this.real+real, this.imag);}/*** Returns a new Complex whose value is {this - subtrahend}** @param subtrahend complex to be subtracted from this* @return {this - subtrahend}*/public Complex sub(Complex subtrahend) {return new Complex(this.real-subtrahend.real, this.imag-subtrahend.imag);}public Complex sub(double real) {return new Complex(this.real-real, this.imag);}/*** Returns a new Complex whose value is {this * multiplicand}** @param multiplicand complex to be multiplied by this* @return {this * multiplicand}*/public Complex mul(Complex multiplicand) {double real = this.real*multiplicand.real - this.imag*multiplicand.imag;double imag = this.real*multiplicand.imag + this.imag*multiplicand.real;return new Complex(real, imag);}public Complex mul(double real) {return new Complex(this.real*real, this.imag*real);}/*** Returns a new Complex whose value is {this / divisor}** @param divisor complex by which this is to be divided* @return {this / divisor}* @throws ArithmeticException if /0*/public Complex div(Complex divisor) {double denominator = divisor.real*divisor.real + divisor.imag*divisor.imag;if (denominator == 0) {throw new ArithmeticException("Complex division by zero!");}double real = (this.real*divisor.real + this.imag*divisor.imag) / denominator;double imag = (this.imag*divisor.real - this.real*divisor.imag) / denominator;return new Complex(real, imag);}public Complex div(double real) {if (real == 0) {throw new ArithmeticException("Complex division by zero!");}return new Complex(this.real/real, this.imag/real);}/*** Returns the modulus value of a complex number ( 复数的模 )** @return length of the vector in 2d plane*/public double abs() {return Math.sqrt(real*real + imag*imag);}/*** Returns the modulus value of a complex number ( 复数的模 )** @return length of the vector in 2d plane*/public double mod() {return Math.sqrt(real*real + imag*imag);}/*** Returns the argument of a complex number ( 复数的辐角 )** @return angle in radians of the vector in 2d plane (-PI~PI)*/public double arg() {return Math.atan2(this.imag, this.real);}/*** Returns the inverse of a complex number ( 复数的倒数 )** @return inverse of this* @throws ArithmeticException ZERO has no inverse.*/public Complex inv() {double denominator = real*real + imag*imag;if (denominator == 0) {throw new ArithmeticException("ZERO has no inverse!");}double real = this.real / denominator;double imag = this.imag / denominator;return new Complex(real, imag);}/*** Returns  the numerical negative value of a complex number** @return {0 - this}*/public Complex neg() {return new Complex(-this.real, -this.imag);}/*** Returns the conjugate of a complex number** @return conjugate of this*/public Complex conj() {return new Complex(this.real, -this.imag);}/*** Returns the square root of a complex number** @return square root of this*/public Complex sqrt() {double mod = this.mod();double sqrt2 = Math.sqrt(2);double real =  Math.sqrt(mod + this.real) / sqrt2;double sgn = Math.signum(this.imag);if (sgn == 0.0) {sgn = 1.0;}double imag = Math.sqrt(mod - this.real) / sqrt2 * Math.signum(sgn);return new Complex(real, imag);}/*** Is this exactly ZERO?** @return true / false*/public boolean isZero() {return this.real == 0 && this.imag == 0;}/*** Is this a pure real number?** @return true / false*/public boolean isReal() {return this.imag == 0;}/*** Is this a pure imaginary number?** @return true / false*/public boolean isImag() {return this.real == 0;}}

ComplexTest

/*** It tests some methods in Complex.** @author Cloudy1225*/
public class ComplexTest {private static final double delta = 1e-6;@Testpublic void testToString() {Complex complex1 = new Complex(2, -3);Complex complex2 = new Complex(2.5, 3.9);Complex complex3 = new Complex(0, -0.8);Complex complex4 = new Complex(1);Complex complex5 = new Complex(0, 0.8);Complex complex6 = Complex.ZERO;System.out.println(complex1);System.out.println(complex2);System.out.println(complex3);System.out.println(complex4);System.out.println(complex5);System.out.println(complex6);}@Testpublic void testDiv() {Complex complex1 = new Complex(10, -10);Complex complex2 = new Complex(3, 4);Complex res = complex1.div(complex2);System.out.println(res);Assert.assertTrue(res.eq(new Complex(-0.4, -2.8)));try {complex1.div(Complex.ZERO);} catch (ArithmeticException e) {e.printStackTrace();}}@Testpublic void testSqrt() {Complex complex1 = new Complex(4);Assert.assertTrue(complex1.sqrt().eq(new Complex(2)));Complex complex2 = new Complex(1, 4);Complex sqrt = complex2.sqrt();System.out.println(sqrt);Complex mul = sqrt.mul(sqrt);System.out.println(mul);Assert.assertTrue(complex2.eq(mul));}@Testpublic void testArg() {Complex complex = new Complex(1, 1);double angel = complex.arg();System.out.println(complex.arg());Assert.assertEquals(complex.arg()*4, Math.PI, delta);}@Testpublic void testParseComplex() {Complex complex1 = Complex.parseComplex("1+5i");Complex complex2 = Complex.parseComplex("12.j+5");Complex complex3 = Complex.parseComplex("1e-3-2e3i");Complex complex4 = Complex.parseComplex("0+1.j");Complex complex5 = Complex.parseComplex(".5");System.out.println(complex1);System.out.println(complex2);System.out.println(complex3);System.out.println(complex4);System.out.println(complex5);try {Complex.parseComplex("0.2+ 3j");} catch (NumberFormatException e) {e.printStackTrace();}try {Complex.parseComplex("0.2+3ja");} catch (NumberFormatException e) {e.printStackTrace();}}}

Java实现Complex复数类及其常见数学计算相关推荐

  1. python定义一个复数类complex、并实现复数相加_用java定义一个复数类Complex,能够创建复数对象,并且实现复数之间的加、减运算...

    题目: 用java定义一个复数类Complex,能够创建复数对象,并且实现复数之间的加.减运算 复数具有实部和虚部两部分,如2+5i就是一个复数,其中2为实部,5i为虚部;两复数相加时,实部与实部相加 ...

  2. 复数类 java_用java写一个复数类Complex

    由于java库中没有提供复数的操作,应同学的需求,写了一个复数的类.有两个构造方法不带参数和带参数的,不带参数时默认实部虚部都为0.还有这些基本的方法,看名字就知道了. public double g ...

  3. java arrays.equals_Java Arrays类的常见使用

    对于数组中有几个常见的操作,是需要大家掌握的,因为在学习java数组时会被频繁使用到.有一些大家在以前有所接触过的,可以再复习一遍,加深此类用法的记忆.本篇为大家总结了三个方法:toString.so ...

  4. 【C++】Complex复数类运算符重载(类的成员函数实现)

    一.复数类运算符重载 <1>分类: 在c++中,有些运算符可以重载,有些不可以重载,详情见下图: 那么,一般用的比较多的有**+.-.*./.=.前置++,- -.后置++,- -.< ...

  5. java实验——设计复数类,成员变量包括实部和虚部,成员方法为实现复数相加。

    设计复数类,成员变量包括实部和虚部,成员方法为实现复数相加. package shiyan.shiyan8;import java.util.*;public class ComplexTest{st ...

  6. java mod函数的使用方法_java 数学计算的具体使用

    java.lang.Math 库提供了常用的数学计算工具 常量 final double E = 2.7182818284590452354; // 自然对数底数 final double PI = ...

  7. 常用工具类 Math:数学计算 Random:生成伪随机数 SecureRandom:生成安全的随机数 2020-2-13

    常用工具类 阅读: 324836 Java的核心库提供了大量的现成的类供我们使用.本节我们介绍几个常用的工具类. Math 顾名思义,Math类就是用来进行数学计算的,它提供了大量的静态方法来便于我们 ...

  8. java简单的复数类_Java练习 SDUT-4303_简单的复数运算(类和对象)

    简单的复数运算(类和对象) Time Limit: 2000 ms Memory Limit: 65536 KiB Problem Description 设计一个类Complex,用于封装对复数的下 ...

  9. Complex复数类

    public class Complex {private double RealPart;//实部 private double ImagePart;//虚部 /* 定义构造函数 */ public ...

最新文章

  1. Masonry 原理与使用说明
  2. 《挖财编程题》求数列的和
  3. codeblocks调试窗口字体大小以及修改主题
  4. 一图感受各种机器学习算法
  5. LeetCode:面试题40. 最小的k个数
  6. DDOS压力测试系统
  7. (江西财经大学第二届程序设计竞赛同步赛)E-是不是复读机
  8. CSS进阶(二)——特性
  9. jquery 封装ajax方法,关于二次封装jquery ajax办法示例详解
  10. 阶段1 语言基础+高级_1-3-Java语言高级_06-File类与IO流_08 转换流_2_编码引出的问题_FileReader读取GBK格式文件...
  11. 【Linux operation 07】 - SUSE 12 SP5系统挂载硬盘
  12. python的def什么意思_「Python基础」def是什么?如何自定义函数def
  13. poj1265 -- Area(皮克定理)
  14. rtx2060为什么叫智商卡_显卡怎么选,GTX1660TI亦是RTX2060?
  15. 如何优化前端页面的LCP?
  16. 中山大学3D游戏设计读书笔记 unity3D Note9
  17. java tld文件配置_Java Web应用因tld文件损坏出现的错误
  18. 笔试题:一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。该题有三种解法:递归的方法求解斐波那契数列、用概率与统计的数学方法解决,3.动态规划
  19. QQ for Mac无法登陆
  20. multiple-media streaming on p2p overlay across oversea network

热门文章

  1. java小朋友猜拳_[Java教程]Java猜拳小游戏(剪刀、石头、布)
  2. (2022)情人节送小仙女什么礼物?Python对口红进行数据分析,那个女孩子会拒绝这样精心挑选的礼物~
  3. 计算机维修人员评价表,信息技术课学生评价表
  4. 大带宽、高速率接口对比---USB、PCIE、SATA、HDMI和以太网等接口
  5. 如何监听小程序返回按钮事件?
  6. SNMP协议的了解与简单的抓包分析
  7. SNMP协议端口区别
  8. TMD的崛起与BAT的恩怨情仇
  9. 【web前端】CSS第二天
  10. SEO实战之提升百度权重和网站PR值的秘籍