Java 复数,3 个类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10098958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Complex Numbers, 3 Classes
提问by user1316703
I'll repeat what I have to do in java, in the way I think I need to think in order to complete this mission. (Sorry, I'm new to programming).
我将重复我在java 中必须做的事情,以我认为我需要思考的方式来完成这个任务。(对不起,我是编程新手)。
First class; define class for complex numbers. I found this fairly easy and my answer is below.
头等舱;为复数定义类。我发现这很容易,我的答案如下。
public class Complex {
private double real;
private double imaginary;
public Complex()
{
this( 0.0, 0.0 );
}
public Complex( double r, double i )
{
real = r;
imaginary = i;
}
}
Second class; add and subtract with public static methods, recalling real and imaginary from first class. This part I found a little bit more challenging as I don't 100% grasp this.
二等舱;使用公共静态方法进行加法和减法,从头等舱中回忆实数和虚数。我发现这部分更具挑战性,因为我不是 100% 掌握这一点。
Public class ComplexArith
public static ComplexAdd(Complex one, Complex two)
return Complex(one.getReal() + two.getReal(), one.getImaginary() + two.getImaginary());
public static ComplexSub(Complex one, Complex two)
return Complex(one.getReal() - two.getReal(), one.getImaginary - two.getImaginary());
The third part is to ask for user input, and add and subtract the set of complex numbers. I'm unfamiliar with this as I've never had to ask for user input in a (0.0,0.0) format.
第三部分是请求用户输入,对复数集合进行加减运算。我对此并不熟悉,因为我从未要求用户输入 (0.0,0.0) 格式。
Any insight on the overall code? Am I even on the right track?
对整体代码有什么见解吗?我是否在正确的轨道上?
EDIT:
编辑:
The first class I banged out. Thanks to you guys.
第一堂课我打了。谢谢你们。
Second class I'm having compiling issues because I'm not fully understanding something.
第二堂课我有编译问题,因为我没有完全理解某些东西。
public class ComplexArith{
public static Complex add(Complex one, Complex two)
{
return Complex(one.getReal() + two.getReal(), one.getImaginary() + two.getImaginary());
}
public static Complex sub(Complex one, Complex two)
{
return Complex(one.getReal() - two.getReal(), one.getImaginary - two.getImaginary());
}
}
I know that one and two need to be defined, but I'm not understanding how to define them. What would I define them as? I thought it was being called from class Complex from double r, double i.
我知道需要定义一和二,但我不明白如何定义它们。我会将它们定义为什么?我认为它是从 double r、double i 的 Complex 类中调用的。
I also thought .getImaginary
was being defined as well in the first class. Here is the first class.
我还认为.getImaginary
在第一堂课中也被定义了。这里是第一堂课。
public class Complex
{
private double real;
private double imaginary;
public Complex()
{
this( 0.0, 0.0 );
}
public Complex( double r, double i )
{
real = r;
imaginary = i;
}
public double getReal() {
return this.real;
}
public double getImaginary() {
return this.imaginary;
}
}
回答by Tim Pote
Well you're on the right track, but you need getters on your Complex
object.
好吧,您走在正确的轨道上,但是您的Complex
对象需要吸气剂。
For example:
例如:
public class Complex
{
private double real;
private double imaginary;
public Complex()
{
this( 0.0, 0.0 );
}
public Complex( double r, double i )
{
real = r;
imaginary = i;
}
public double getReal() {
return this.real;
}
public double getImaginary() {
return this.imaginary;
}
}
You also need return types on your methods:
您还需要方法的返回类型:
public class ComplexArith
{
public static Complex complexAdd(Complex one, Complex two) {
return Complex(one.getReal() + two.getReal(),
one.getImaginary() + two.getImaginary());
}
public static Complex complexSub(Complex one, Complex two) {
return Complex(one.getReal() - two.getReal(),
one.getImaginary - two.getImaginary());
}
}
Also, it has nothing to do with the functionality of your program, but it's customary to have your methods use camelCase
. So your methods should look like this:
此外,它与您的程序的功能无关,但习惯上让您的方法使用camelCase
. 所以你的方法应该是这样的:
public static Complex complexAdd(Complex one, Complex two) {
return Complex(one.getReal() + two.getReal(),
one.getImaginary() + two.getImaginary());
}
回答by duffymo
Personally, I'd put those arithmetic operations in the Complex class. Those are truly operations on Complex numbers, so I wouldn't encapsulate them outside the Complex class.
就个人而言,我会将这些算术运算放在 Complex 类中。这些是对复数的真正操作,因此我不会将它们封装在 Complex 类之外。
I'd think about making Complex immutable. It's thread safe that way.
我会考虑使 Complex 不可变。这样是线程安全的。
I like the static add, sub, mul, div methods. Be sure that they return a Complex (they don't now). Other methods, like cosine, sine, etc. might belong in a Math class in your complex package. See the java.lang.Math for an example for real numbers.
我喜欢静态的 add、sub、mul、div 方法。确保他们返回一个 Complex (他们现在没有)。其他方法,如余弦、正弦等,可能属于复杂包中的 Math 类。有关实数的示例,请参阅 java.lang.Math。
You need to return "new Complex". The code you wrote won't compile.
您需要返回“新综合体”。你写的代码不会编译。
回答by user2821468
this is my implementation, i do all on one class:
这是我的实现,我在一个类中完成所有操作:
package name.puzio.math;
public final class ComplexNumber {
private final double imaginary;
private final double real;
@Override
public final boolean equals(Object object) {
if (!(object instanceof ComplexNumber))
return false;
ComplexNumber a = (ComplexNumber) object;
return (real == a.real) && (imaginary == a.imaginary);
}
public ComplexNumber(double real, double imaginary) {
this.imaginary = imaginary;
this.real = real;
}
public static final ComplexNumber createPolar(double amount, double angel) {
return new ComplexNumber(amount * Math.cos(angel), amount * Math.sin(angel));
}
public final double getImaginary() {
return imaginary;
}
public final double getReal() {
return real;
}
public final double getAmount() {
return Math.sqrt((real * real) + (imaginary * imaginary));
}
public final double getAngle() {
return Math.atan2(imaginary, real);
}
public final ComplexNumber add(ComplexNumber b) {
return add(this, b);
}
public final ComplexNumber sub(ComplexNumber b) {
return sub(this, b);
}
public final ComplexNumber div(ComplexNumber b) {
return div(this, b);
}
public final ComplexNumber mul(ComplexNumber b) {
return mul(this, b);
}
public final ComplexNumber conjugation() {
return conjugation(this);
}
/**
* Addition:
* @param a
* @param b
* @return
*/
private final static ComplexNumber add(ComplexNumber a, ComplexNumber b) {
return new ComplexNumber(a.real + b.real, a.imaginary + b.imaginary);
}
/**
* Subtraktion:
* @param a
* @param b
* @return
*/
private final static ComplexNumber sub(ComplexNumber a, ComplexNumber b) {
return new ComplexNumber(a.real - b.real, a.imaginary - b.imaginary);
}
/**
* Multiplikation:
* @param a
* @param b
* @return
**/
private final static ComplexNumber mul(ComplexNumber a, ComplexNumber b) {
return new ComplexNumber((a.real * b.real) - (a.imaginary * b.imaginary), (a.imaginary * b.real) + (a.real * b.imaginary));
}
/**
* Division:
* @param a
* @param b
* @return
**/
private final static ComplexNumber div(ComplexNumber a, ComplexNumber b) {
double d = (b.real * b.real) + (b.imaginary * b.imaginary);
if (d == 0)
return new ComplexNumber(Double.NaN, Double.NaN);
return new ComplexNumber(((a.real * b.real) + (a.imaginary * b.imaginary)) / d, ((a.imaginary * b.real) - (a.real * b.imaginary)) / d);
}
/**
* Konjugation:
* @param a
* @return
**/
private final static ComplexNumber conjugation(ComplexNumber a) {
return new ComplexNumber(a.real, -a.imaginary);
}
}
回答by Abdul Fatir
Though this already been answered I thought people may benefit by the following class which does a lot of functions related to Complex Numbers.
虽然这已经得到了回答,但我认为人们可能会从以下课程中受益,该课程执行许多与复数相关的功能。
This has been released under MIT License and the GitHub project is here.
这是在 MIT 许可下发布的,GitHub 项目在这里。
/**
* <code>ComplexNumber</code> is a class which implements complex numbers in Java.
* It includes basic operations that can be performed on complex numbers such as,
* addition, subtraction, multiplication, conjugate, modulus and squaring.
* The data type for Complex Numbers.
* <br /><br />
* The features of this library include:<br />
* <ul>
* <li>Arithmetic Operations (addition, subtraction, multiplication, division)</li>
* <li>Complex Specific Operations - Conjugate, Inverse, Absolute/Magnitude, Argument/Phase</li>
* <li>Trigonometric Operations - sin, cos, tan, cot, sec, cosec</li>
* <li>Mathematical Functions - exp</li>
* <li>Complex Parsing of type x+yi</li>
* </ul>
*
* @author Abdul Fatir
* @version 1.1
*
*/
public class ComplexNumber
{
/**
* Used in <code>format(int)</code> to format the complex number as x+yi
*/
public static final int XY = 0;
/**
* Used in <code>format(int)</code> to format the complex number as R.cis(theta), where theta is arg(z)
*/
public static final int RCIS = 1;
/**
* The real, Re(z), part of the <code>ComplexNumber</code>.
*/
private double real;
/**
* The imaginary, Im(z), part of the <code>ComplexNumber</code>.
*/
private double imaginary;
/**
* Constructs a new <code>ComplexNumber</code> object with both real and imaginary parts 0 (z = 0 + 0i).
*/
public ComplexNumber()
{
real = 0.0;
imaginary = 0.0;
}
/**
* Constructs a new <code>ComplexNumber</code> object.
* @param real the real part, Re(z), of the complex number
* @param imaginary the imaginary part, Im(z), of the complex number
*/
public ComplexNumber(double real, double imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
/**
* Adds another <code>ComplexNumber</code> to the current complex number.
* @param z the complex number to be added to the current complex number
*/
public void add(ComplexNumber z)
{
set(add(this,z));
}
/**
* Subtracts another <code>ComplexNumber</code> from the current complex number.
* @param z the complex number to be subtracted from the current complex number
*/
public void subtract(ComplexNumber z)
{
set(subtract(this,z));
}
/**
* Multiplies another <code>ComplexNumber</code> to the current complex number.
* @param z the complex number to be multiplied to the current complex number
*/
public void multiply(ComplexNumber z)
{
set(multiply(this,z));
}
/**
* Divides the current <code>ComplexNumber</code> by another <code>ComplexNumber</code>.
* @param z the divisor
*/
public void divide(ComplexNumber z)
{
set(divide(this,z));
}
/**
* Sets the value of current complex number to the passed complex number.
* @param z the complex number
*/
public void set(ComplexNumber z)
{
this.real = z.real;
this.imaginary = z.imaginary;
}
/**
* Adds two <code>ComplexNumber</code>.
* @param z1 the first <code>ComplexNumber</code>.
* @param z2 the second <code>ComplexNumber</code>.
* @return the resultant <code>ComplexNumber</code> (z1 + z2).
*/
public static ComplexNumber add(ComplexNumber z1, ComplexNumber z2)
{
return new ComplexNumber(z1.real + z2.real, z1.imaginary + z2.imaginary);
}
/**
* Subtracts one <code>ComplexNumber</code> from another.
* @param z1 the first <code>ComplexNumber</code>.
* @param z2 the second <code>ComplexNumber</code>.
* @return the resultant <code>ComplexNumber</code> (z1 - z2).
*/
public static ComplexNumber subtract(ComplexNumber z1, ComplexNumber z2)
{
return new ComplexNumber(z1.real - z2.real, z1.imaginary - z2.imaginary);
}
/**
* Multiplies one <code>ComplexNumber</code> to another.
* @param z1 the first <code>ComplexNumber</code>.
* @param z2 the second <code>ComplexNumber</code>.
* @return the resultant <code>ComplexNumber</code> (z1 * z2).
*/
public static ComplexNumber multiply(ComplexNumber z1, ComplexNumber z2)
{
double _real = z1.real*z2.real - z1.imaginary*z2.imaginary;
double _imaginary = z1.real*z2.imaginary + z1.imaginary*z2.real;
return new ComplexNumber(_real,_imaginary);
}
/**
* Divides one <code>ComplexNumber</code> by another.
* @param z1 the first <code>ComplexNumber</code>.
* @param z2 the second <code>ComplexNumber</code>.
* @return the resultant <code>ComplexNumber</code> (z1 / z2).
*/
public static ComplexNumber divide(ComplexNumber z1, ComplexNumber z2)
{
ComplexNumber output = multiply(z1,z2.conjugate());
double div = Math.pow(z2.mod(),2);
return new ComplexNumber(output.real/div,output.imaginary/div);
}
/**
* The complex conjugate of the current complex number.
* @return a <code>ComplexNumber</code> object which is the conjugate of the current complex number
*/
public ComplexNumber conjugate()
{
return new ComplexNumber(this.real,-this.imaginary);
}
/**
* The modulus, magnitude or the absolute value of current complex number.
* @return the magnitude or modulus of current complex number
*/
public double mod()
{
return Math.sqrt(Math.pow(this.real,2) + Math.pow(this.imaginary,2));
}
/**
* The square of the current complex number.
* @return a <code>ComplexNumber</code> which is the square of the current complex number.
*/
public ComplexNumber square()
{
double _real = this.real*this.real - this.imaginary*this.imaginary;
double _imaginary = 2*this.real*this.imaginary;
return new ComplexNumber(_real,_imaginary);
}
/**
* @return the complex number in x + yi format
*/
@Override
public String toString()
{
String re = this.real+"";
String im = "";
if(this.imaginary < 0)
im = this.imaginary+"i";
else
im = "+"+this.imaginary+"i";
return re+im;
}
/**
* Calculates the exponential of the <code>ComplexNumber</code>
* @param z The input complex number
* @return a <code>ComplexNumber</code> which is e^(input z)
*/
public static ComplexNumber exp(ComplexNumber z)
{
double a = z.real;
double b = z.imaginary;
double r = Math.exp(a);
a = r*Math.cos(b);
b = r*Math.sin(b);
return new ComplexNumber(a,b);
}
/**
* Calculates the <code>ComplexNumber</code> to the passed integer power.
* @param z The input complex number
* @param power The power.
* @return a <code>ComplexNumber</code> which is (z)^power
*/
public static ComplexNumber pow(ComplexNumber z, int power)
{
ComplexNumber output = new ComplexNumber(z.getRe(),z.getIm());
for(int i = 1; i < power; i++)
{
double _real = output.real*z.real - output.imaginary*z.imaginary;
double _imaginary = output.real*z.imaginary + output.imaginary*z.real;
output = new ComplexNumber(_real,_imaginary);
}
return output;
}
/**
* Calculates the sine of the <code>ComplexNumber</code>
* @param z the input complex number
* @return a <code>ComplexNumber</code> which is the sine of z.
*/
public static ComplexNumber sin(ComplexNumber z)
{
double x = Math.exp(z.imaginary);
double x_inv = 1/x;
double r = Math.sin(z.real) * (x + x_inv)/2;
double i = Math.cos(z.real) * (x - x_inv)/2;
return new ComplexNumber(r,i);
}
/**
* Calculates the cosine of the <code>ComplexNumber</code>
* @param z the input complex number
* @return a <code>ComplexNumber</code> which is the cosine of z.
*/
public static ComplexNumber cos(ComplexNumber z)
{
double x = Math.exp(z.imaginary);
double x_inv = 1/x;
double r = Math.cos(z.real) * (x + x_inv)/2;
double i = -Math.sin(z.real) * (x - x_inv)/2;
return new ComplexNumber(r,i);
}
/**
* Calculates the tangent of the <code>ComplexNumber</code>
* @param z the input complex number
* @return a <code>ComplexNumber</code> which is the tangent of z.
*/
public static ComplexNumber tan(ComplexNumber z)
{
return divide(sin(z),cos(z));
}
/**
* Calculates the co-tangent of the <code>ComplexNumber</code>
* @param z the input complex number
* @return a <code>ComplexNumber</code> which is the co-tangent of z.
*/
public static ComplexNumber cot(ComplexNumber z)
{
return divide(new ComplexNumber(1,0),tan(z));
}
/**
* Calculates the secant of the <code>ComplexNumber</code>
* @param z the input complex number
* @return a <code>ComplexNumber</code> which is the secant of z.
*/
public static ComplexNumber sec(ComplexNumber z)
{
return divide(new ComplexNumber(1,0),cos(z));
}
/**
* Calculates the co-secant of the <code>ComplexNumber</code>
* @param z the input complex number
* @return a <code>ComplexNumber</code> which is the co-secant of z.
*/
public static ComplexNumber cosec(ComplexNumber z)
{
return divide(new ComplexNumber(1,0),sin(z));
}
/**
* The real part of <code>ComplexNumber</code>
* @return the real part of the complex number
*/
public double getRe()
{
return this.real;
}
/**
* The imaginary part of <code>ComplexNumber</code>
* @return the imaginary part of the complex number
*/
public double getIm()
{
return this.imaginary;
}
/**
* The argument/phase of the current complex number.
* @return arg(z) - the argument of current complex number
*/
public double getArg()
{
return Math.atan2(imaginary,real);
}
/**
* Parses the <code>String</code> as a <code>ComplexNumber</code> of type x+yi.
* @param s the input complex number as string
* @return a <code>ComplexNumber</code> which is represented by the string.
*/
public static ComplexNumber parseComplex(String s)
{
s = s.replaceAll(" ","");
ComplexNumber parsed = null;
if(s.contains(String.valueOf("+")) || (s.contains(String.valueOf("-")) && s.lastIndexOf('-') > 0))
{
String re = "";
String im = "";
s = s.replaceAll("i","");
s = s.replaceAll("I","");
if(s.indexOf('+') > 0)
{
re = s.substring(0,s.indexOf('+'));
im = s.substring(s.indexOf('+')+1,s.length());
parsed = new ComplexNumber(Double.parseDouble(re),Double.parseDouble(im));
}
else if(s.lastIndexOf('-') > 0)
{
re = s.substring(0,s.lastIndexOf('-'));
im = s.substring(s.lastIndexOf('-')+1,s.length());
parsed = new ComplexNumber(Double.parseDouble(re),-Double.parseDouble(im));
}
}
else
{
// Pure imaginary number
if(s.endsWith("i") || s.endsWith("I"))
{
s = s.replaceAll("i","");
s = s.replaceAll("I","");
parsed = new ComplexNumber(0, Double.parseDouble(s));
}
// Pure real number
else
{
parsed = new ComplexNumber(Double.parseDouble(s),0);
}
}
return parsed;
}
/**
* Checks if the passed <code>ComplexNumber</code> is equal to the current.
* @param z the complex number to be checked
* @return true if they are equal, false otherwise
*/
@Override
public final boolean equals(Object z)
{
if (!(z instanceof ComplexNumber))
return false;
ComplexNumber a = (ComplexNumber) z;
return (real == a.real) && (imaginary == a.imaginary);
}
/**
* The inverse/reciprocal of the complex number.
* @return the reciprocal of current complex number.
*/
public ComplexNumber inverse()
{
return divide(new ComplexNumber(1,0),this);
}
/**
* Formats the Complex number as x+yi or r.cis(theta)
* @param format_id the format ID <code>ComplexNumber.XY</code> or <code>ComplexNumber.RCIS</code>.
* @return a string representation of the complex number
* @throws IllegalArgumentException if the format_id does not match.
*/
public String format(int format_id) throws IllegalArgumentException
{
String out = "";
if(format_id == XY)
out = toString();
else if(format_id == RCIS)
{
out = mod()+" cis("+getArg()+")";
}
else
{
throw new IllegalArgumentException("Unknown Complex Number format.");
}
return out;
}
}
回答by Marc
Or....... you could just dispense with all of this nonsense and just use the Apache Commons library, which works better than anything here and includes essential operations like complex exponentiation.
或者......你可以放弃所有这些废话,只使用 Apache Commons 库,它比这里的任何东西都好用,并且包括复杂的取幂等基本操作。
https://commons.apache.org/proper/commons-math/userguide/complex.html
https://commons.apache.org/proper/commons-math/userguide/complex.html
but only if you don't feel like re-inventing the wheel.
但前提是你不想重新发明轮子。
回答by QuantumMechanic
You're somewhat on the right track given what you state are the assignments.
考虑到您所说的任务,您在某种程度上走在正确的轨道上。
However, in your second class you are calling getReal()
and getImaginary()
methods on Complex
objects. But their definitions don't show up anywhere in the Complex
class definition.
然而,在你的第二类,你在呼唤getReal()
和getImaginary()
对方法Complex
的对象。但是它们的定义不会出现在Complex
类定义中的任何地方。
And your methods in ComplexArith
have no return types.
并且您的方法ComplexArith
没有返回类型。
Those alone will prevent your code from compiling as-is.
仅这些就会阻止您的代码按原样编译。
回答by cebarrett
The correctway to convert a String
in the format (r,i)
into a Complex
would be to use a regular expression. However if you're new to programming your instructor might suspect you copied that solution from the Internet :) Try something like this:
将格式中的a转换为 a的正确方法是使用正则表达式。但是,如果您不熟悉编程,您的教师可能会怀疑您从 Internet 复制了该解决方案 :) 尝试如下操作:String
(r,i)
Complex
public static Complex fromString(String str) {
str = str.substring(1, str.length() - 1);
String[] parts = str.split(",");
double r = Double.valueOf(parts[0]);
double i = Double.valueOf(parts[1]);
return new Complex(r, i);
}
You can find more info about the Java String class here: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
您可以在此处找到有关 Java String 类的更多信息:http: //docs.oracle.com/javase/6/docs/api/java/lang/String.html
回答by Dimiter P
This is not correct!
这是不正确的!
public static ComplexNumber exp(ComplexNumber z)
{
double a = z.real;
double b = z.imaginary;
double r = Math.exp(a);
a = r*Math.cos(b);
b = r*Math.sin(b);
return new ComplexNumber(a,b);
}
should be
应该
public static ComplexNumber exp(ComplexNumber z)
{
double theta = Math.atan2(r.real/r.imag);
double r = mod();
double a = r*Math.cos(theta );
double b = r*Math.sin(theta );
return new ComplexNumber(a,b);
}