c#中的复数

本文关键字: | 更新日期: 2023-09-27 18:09:00

我有一个写复数实现的任务:-

Complex c = new Complex(1.2,2.0)

写出实数和虚数的性质,得到复数的实部和虚部。它们是这样使用的:

double x = c.Real;
写一个方法将两个复数相加并返回它们的和。实部是两个实部的和,虚部是两个虚部的和。
Complex c = c1.Sum(c2);

写一个计算两个复数之积的方法。如果一个数有组分x1y1,第二个数有组分x2y2:

积实部= x1 *x2 - y1 *y2;虚部= x1 * y2 + x2 *y1;

所以我知道并且对手动复数很有信心,例如4 +5i其中5i是虚数,

我的问题是,我不知道如何让应用程序知道哪一个是虚构的,除非我输入一个预定义的虚数..当我这样做的时候,尽管"应用"失去了它的价值,因为它不是一个复数,只是一些随机的计算应用。基本上我不知道如何继续…由于

c#中的复数

从你的问题看来,你对复数的构造感到困惑。这里有一个模板可以让你开始。

public class Complex
{
    public Complex(double real, double imaginary)
    {
    }
}

则以

开头
 static void Main(string[] args)
 {
    Complex c1 = new Complex(1.2,2.0)
    Complex c2 = new Complex(1,3.0)
    Complex c3 = c1.Sum(c2);
    Console.WriteLine(c3.Real);
    Console.WriteLine(c3.Imaginary);
 }

并使其工作(对于初学者,输入任何您喜欢的数字)

由于这个问题在一段时间前被问到,但我相信还有其他人对这个话题感兴趣,我决定在c#中发布我最近实现的复数的实现。

因为复数是值类型,我使用一个结构体,而不是一个类(struct更快的在这种情况下,我发现一个简单的应用程序的帮助下我写运行曼德布洛特算法(答案见下面的链接)来衡量)和重载操作符像+, -, *, /以及比较运算符<, >, =, !=, ==所以你可以无缝地使用它们(不过由于复数是二维,< >将比较方量,而==!=比较是否相等)。

我使用了双精度,因为分形图形等要求精度很高。但是你也可以使用单精度,如果这对你的应用程序来说是足够的。

注意,这也需要覆盖GetHashCode()Equals(object obj)。我还重载了++--操作符,尽管在复杂的世界中有几种可能的方法来解释这一点:增量/递减实数和虚数部分或只是其中之一?

我还创建了元组(a, bi)和复数之间的隐式转换,因此您可以轻松地初始化它们,如:

complex a = (1, 2), b = (3, 4); // via tuples (re, im)

你甚至可以解析这样的字符串:

string input = Console.ReadLine();
if (!complex.TryParse(input, out complex c)) 
    Console.WriteLine("Syntax error"); 
else 
    Console.WriteLine($"Parsed value for c = {c}");

那么你可以像

那样简单地使用它们
var w = a - b;  Console.WriteLine($"a - b = {w}");
var x = a + b;  Console.WriteLine($"a + b = {x}");
var y = a * b;  Console.WriteLine($"a * b = {y}");
var z = a / b;  Console.WriteLine($"a / b = {z}");

输出

a - b = -2 - 2i
A + b = 4 + 1
A * b = -5 + 10i
A/b = 0.44 + 0.08i

你甚至可以写一个for循环,就像(注意你有2维!):

for (complex u = (0,0); u <= (5, 5); u.Re++, u.Im++)
{
    Console.WriteLine(u);
}

如果比较也是可能的:

if (u==(1, 1)) Console.WriteLine("u == 1+i");

所需的类实现如下:

/// <summary>
/// Complex numbers
/// Written by Matt, 2022
/// </summary>
struct complex
{
    public double Re, Im;
    public complex(double re, double im)
    {
        this.Re = re; this.Im = im;
    }

    public static complex operator ++(complex c) { ++c.Re; ++c.Im; return c; } // not the only way one can implement this
    public static complex operator --(complex c) { --c.Re; --c.Im; return c; } // not the only way one can implement this
    public static complex operator +(complex a, complex b) => new complex(a.Re + b.Re, a.Im + b.Im);
    public static complex operator -(complex a, complex b) => new complex(a.Re - b.Re, a.Im - b.Im);
    public static double AmountSqr(complex c) => c.Re * c.Re + c.Im + c.Im;
    public static double Amount(complex c) => Math.Sqrt(AmountSqr(c));
    /// <summary>Compares the amount of both complex numbers, returns true if |a|<|b|.</summary>
    public static bool operator <(complex a, complex b) => AmountSqr(a) < AmountSqr(b);
    /// <summary>Compares the amount of both complex numbers, returns true if |a|>|b|.</summary>
    public static bool operator >(complex a, complex b) => AmountSqr(a) > AmountSqr(b);
    /// <summary>Compares the both complex numbers, returns true if a == b.</summary>
    public static bool operator ==(complex a, complex b) => (a.Re == b.Re && a.Im == b.Im);
    /// <summary>Compares the both complex numbers, returns true if a != b.</summary>
    public static bool operator !=(complex a, complex b) => (a.Re != b.Re || a.Im != b.Im);

    // (a+bi)(c+di) = ac-bd + (ad+bc)i  
    public static complex operator *(complex a, complex b) 
            => new complex(a.Re*b.Re-a.Im*b.Im, a.Re*b.Im+a.Im*b.Re);
    // (a+bi)/(c+di) = (ac+bd)/(c*c + d*d) + i(bc-ad)/(c*c + d*d)
    public static complex operator /(complex a, complex b)
    {
        var divisor = (b.Re * b.Re + b.Im * b.Im);
        return new complex((a.Re*b.Re+a.Im*b.Im)/divisor, (a.Im*b.Re-a.Re*b.Im)/divisor);
    }
    
    public static implicit operator complex((double real, double imag) c) 
            => new complex(c.real, c.imag); // via tuples (re, im)
    public override string ToString() 
        => $"{this.Re.ToString().Trim()} {(this.Im < 0 ? "-" : "+")} {Math.Abs(this.Im)}i";
    
    /// <summary>Tries to convert string expressions like "2+3i" or "5-7i" to complex</summary>
    public static bool TryParse(string complexNr, out complex result) 
    {
        bool success = false;
        result = (0, 0);
        try
        {
            result = Parse(complexNr);
            success = true;
        } catch {}
        return success;
    }
    /// <summary>Converts string expressions like "2+3i" or "5-7i" to complex</summary>
    public static complex Parse(string complexNr)
    {
        complex result = (0, 0);
        try
        {
            if (complexNr.Contains("-")) complexNr = complexNr.Replace("-", "+-");
            var tr = complexNr.Split("+").Select(s => s.Trim()).ToArray();
            var realStr = tr[0]; var imagStr = tr[1].TrimEnd('i').Trim();
            result = (double.Parse(realStr), double.Parse(imagStr));
        } 
        catch (Exception ex)
        {
            throw new SyntaxErrorException("Invalid syntax for complex number. Allowed is 'a+bi' or 'a-bi'", ex);   
        }
        return result;
    }
    
    public override bool Equals(object obj)
    {
        return (obj == null) ? false : (this == (complex)obj);
    }
    public override int GetHashCode()
    {
        var hash = new HashCode();
        hash.Add(this.Re); hash.Add(this.Im);
        return hash.ToHashCode();
    }
}

引用Mandelbrot算法来衡量"复杂"的性能。库):

  1. Mandelbrot集合(Python,但c#程序员也可以理解)
  2. Mandelbrot算法(伪代码)

"我不确定如何让应用程序知道哪个是虚构的"——这里有一个方法:

        Console.WriteLine("Input the real part of the complex number:");
        var real = double.Parse(Console.ReadLine());
        Console.WriteLine("Input the imaginary part of the complex number:");
        var imaginary = double.Parse(Console.ReadLine());
        var complexNumber = new Complex(real, imaginary);

什么是复数?它是一个有实数部分和虚数部分的数。虚部本身是一个实数乘以这个奇特的虚常数i使得i * i = -1。没有更多的东西了,所以这样实现它。为什么这会让你的代码失去价值呢?

public struct Complex
{
    public static readonly ImaginaryOne = new Complex(0, 1);
    public doube Real { get; }
    public double Imaginary { get; }
    public Complex(double real, double imaginary)
    {
        Real = real;
        Imaginary = imaginary;
    }
}

相关文章:
  • 没有找到相关文章