Rust 复数运算,重载加减乘除运算

eb88291a18a94ba4ace118fb4e46ef23.png

复数

基本概念

复数定义

由实数部分和虚数部分所组成的数,形如a+bi 。

其中a、b为实数,i 为“虚数单位”,i 的平方等于-1。

a、b分别叫做复数a+bi的实部和虚部。

当b=0时,a+bi=a 为实数;当b≠0时,a+bi 又称虚数;

当b≠0、a=0时,bi 称为纯虚数。

实数和虚数都是复数的子集。如同实数可以在数轴上表示一样复数也可以在平面上表示,复数x+yi以坐标点(x,y)来表示。表示复数的平面称为“复平面”。

复数相等

两个复数不能比较大小,但当个两个复数的实部和虚部分别相等时,即表示两个复数相等。

共轭复数

如果两个复数的实部相等,虚部互为相反数,那么这两个复数互为共轭复数。

复数的模

复数的实部与虚部的平方和的正的平方根的值称为该复数的模,数学上用与绝对值“|z|”相同的符号来表示。虽然从定义上是不相同的,但两者的物理意思都表示“到原点的距离”。

复数的四则运算

加法(减法)法则

复数的加法法则:设z1=a+bi,z2 =c+di是任意两个复数。两者和的实部是原来两个复数实部的和,它的虚部是原来两个虚部的和。两个复数的和依然是复数。

即(a+bi)±(c+di)=(a±c)+(b±d)

乘法法则

复数的乘法法则:把两个复数相乘,类似两个多项式相乘,结果中i2=-1,把实部与虚部分别合并。两个复数的积仍然是一个复数。

即(a+bi)(c+di)=(ac-bd)+(bc+ad)i

除法法则

复数除法法则:满足(c+di)(x+yi)=(a+bi)的复数x+yi(x,y∈R)叫复数a+bi除以复数c+di的商。

运算方法:可以把除法换算成乘法做,将分子分母同时乘上分母的共轭复数,再用乘法运算。

复数的Rust代码实现

结构定义

Rust语言中,没有像python一样内置complex复数数据类型,我们可以用两个浮点数分别表示复数的实部和虚部,自定义一个结构数据类型,表示如下:

struct Complex {
    real: f64,
    imag: f64,
}

示例代码:

#[derive(Debug)]
struct Complex {
    real: f64,
    imag: f64,
}

impl Complex {  
    fn new(real: f64, imag: f64) -> Self {
        Complex { real, imag }  
    }
}

fn main() {  
    let z = Complex::new(3.0, 4.0);
    println!("{:?}", z);
    println!("{} + {}i", z.real, z.imag);
}

注意:#[derive(Debug)] 自动定义了复数结构的输出格式,如以上代码输出如下:

Complex { real: 3.0, imag: 4.0 }
3 + 4i

重载四则运算

复数数据结构不能直接用加减乘除来做复数运算,需要导入标准库ops的运算符:

use std::ops::{Add, Sub, Mul, Div, Neg};

Add, Sub, Mul, Div, Neg 分别表示加减乘除以及相反数,类似C++或者python语言中“重载运算符”的概念。

根据复数的运算法则,写出对应代码:

fn add(self, other: Complex) -> Complex {
    Complex {
        real: self.real + other.real,
        imag: self.imag + other.imag,
    }  
}  

fn sub(self, other: Complex) -> Complex {
    Complex {  
        real: self.real - other.real,
        imag: self.imag - other.imag,
    }  

fn mul(self, other: Complex) -> Complex {  
    let real = self.real * other.real - self.imag * other.imag;
    let imag = self.real * other.imag + self.imag * other.real;
    Complex { real, imag }  
}  

fn div(self, other: Complex) -> Complex {
    let real = (self.real * other.real + self.imag * other.imag) / (other.real * other.real + other.imag * other.imag);
    let imag = (self.imag * other.real - self.real * other.imag) / (other.real * other.real + other.imag * other.imag);
    Complex { real, imag }
}

fn neg(self) -> Complex {
    Complex {
        real: -self.real,
        imag: -self.imag,
    }
}

Rust 重载运算的格式,请见如下示例代码:

use std::ops::{Add, Sub, Mul, Div, Neg};

#[derive(Clone, Debug, PartialEq)]
struct Complex {
    real: f64,
    imag: f64,
}

impl Complex {  
    fn new(real: f64, imag: f64) -> Self {
        Complex { real, imag }  
    }
  
    fn conj(&self) -> Self {
        Complex { real: self.real, imag: -self.imag }
    }

    fn abs(&self) -> f64 {
        (self.real * self.real + self.imag * self.imag).sqrt()
    }
}

fn abs(z: Complex) -> f64 {
    (z.real * z.real + z.imag * z.imag).sqrt()
}

impl Add<Complex> for Complex {
    type Output = Complex;

    fn add(self, other: Complex) -> Complex {
        Complex {
            real: self.real + other.real,
            imag: self.imag + other.imag,
        }  
    }  
}  
  
impl Sub<Complex> for Complex {
    type Output = Complex;
  
    fn sub(self, other: Complex) -> Complex {
        Complex {  
            real: self.real - other.real,
            imag: self.imag - other.imag,
        }  
    } 
}  
  
impl Mul<Complex> for Complex {
    type Output = Complex;  
  
    fn mul(self, other: Complex) -> Complex {  
        let real = self.real * other.real - self.imag * other.imag;
        let imag = self.real * other.imag + self.imag * other.real;
        Complex { real, imag }  
    }  
}

impl Div<Complex> for Complex {
    type Output = Complex;
  
    fn div(self, other: Complex) -> Complex {
        let real = (self.real * other.real + self.imag * other.imag) / (other.real * other.real + other.imag * other.imag);
        let imag = (self.imag * other.real - self.real * other.imag) / (other.real * other.real + other.imag * other.imag);
        Complex { real, imag }
    }
}  
  
impl Neg for Complex {
    type Output = Complex;
  
    fn neg(self) -> Complex {
        Complex {
            real: -self.real,
            imag: -self.imag,
        }
    }
}

fn main() {  
    let z1 = Complex::new(2.0, 3.0);
    let z2 = Complex::new(3.0, 4.0);
    let z3 = Complex::new(3.0, -4.0);

    // 复数的四则运算
    let complex_add = z1.clone() + z2.clone();
    println!("{:?} + {:?} = {:?}", z1, z2, complex_add);

    let complex_sub = z1.clone() - z2.clone();
    println!("{:?} - {:?} = {:?}", z1, z2, complex_sub);

    let complex_mul = z1.clone() * z2.clone();
    println!("{:?} * {:?} = {:?}", z1, z2, complex_mul);

    let complex_div = z2.clone() / z3.clone();
    println!("{:?} / {:?} = {:?}", z1, z2, complex_div);

    // 对比两个复数是否相等
    println!("{:?}", z1 == z2);
    // 共轭复数
    println!("{:?}", z2 == z3.conj());
    // 复数的相反数
    println!("{:?}", z2 == -z3.clone() + Complex::new(6.0,0.0));

    // 复数的模
    println!("{}", z1.abs());
    println!("{}", z2.abs());
    println!("{}", abs(z3));
}

输出:

Complex { real: 2.0, imag: 3.0 } + Complex { real: 3.0, imag: 4.0 } = Complex { real: 5.0, imag: 7.0 }
Complex { real: 2.0, imag: 3.0 } - Complex { real: 3.0, imag: 4.0 } = Complex { real: -1.0, imag: -1.0 }
Complex { real: 2.0, imag: 3.0 } * Complex { real: 3.0, imag: 4.0 } = Complex { real: -6.0, imag: 17.0 }
Complex { real: 2.0, imag: 3.0 } / Complex { real: 3.0, imag: 4.0 } = Complex { real: -0.28, imag: 0.96 }
false
true
true
3.605551275463989
5
5

示例代码中,同时还定义了复数的模 abs(),共轭复数 conj()。

两个复数的相等比较 z1 == z2,需要 #[derive(PartialEq)] 支持。

自定义 trait Display

复数结构的原始 Debug trait 表达的输出格式比较繁复,如:

Complex { real: 2.0, imag: 3.0 } + Complex { real: 3.0, imag: 4.0 } = Complex { real: 5.0, imag: 7.0 }

想要输出和数学中相同的表达(如 a + bi),需要自定义一个 Display trait,代码如下:

impl std::fmt::Display for Complex {
    fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        if self.imag == 0.0 {
            formatter.write_str(&format!("{}", self.real))
        } else {
            let (abs, sign) = if self.imag > 0.0 {  
                (self.imag, "+" )
            } else {
                (-self.imag, "-" )
            };
            if abs == 1.0 {
                formatter.write_str(&format!("({} {} i)", self.real, sign))
            } else {
                formatter.write_str(&format!("({} {} {}i)", self.real, sign, abs))
            }
        }
    }
}

输出格式分三种情况:虚部为0,正数和负数。另外当虚部绝对值为1时省略1仅输出i虚数单位。

完整代码如下:

use std::ops::{Add, Sub, Mul, Div, Neg};

#[derive(Clone, PartialEq)]
struct Complex {
    real: f64,
    imag: f64,
}

impl std::fmt::Display for Complex {
    fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        if self.imag == 0.0 {
            formatter.write_str(&format!("{}", self.real))
        } else {
            let (abs, sign) = if self.imag > 0.0 {  
                (self.imag, "+" )
            } else {
                (-self.imag, "-" )
            };
            if abs == 1.0 {
                formatter.write_str(&format!("({} {} i)", self.real, sign))
            } else {
                formatter.write_str(&format!("({} {} {}i)", self.real, sign, abs))
            }
        }
    }
}

impl Complex {  
    fn new(real: f64, imag: f64) -> Self {
        Complex { real, imag }  
    }
  
    fn conj(&self) -> Self {
        Complex { real: self.real, imag: -self.imag }
    }

    fn abs(&self) -> f64 {
        (self.real * self.real + self.imag * self.imag).sqrt()
    }
}

fn abs(z: Complex) -> f64 {
    (z.real * z.real + z.imag * z.imag).sqrt()
}

impl Add<Complex> for Complex {
    type Output = Complex;

    fn add(self, other: Complex) -> Complex {
        Complex {
            real: self.real + other.real,
            imag: self.imag + other.imag,
        }  
    }  
}  
  
impl Sub<Complex> for Complex {
    type Output = Complex;
  
    fn sub(self, other: Complex) -> Complex {
        Complex {  
            real: self.real - other.real,
            imag: self.imag - other.imag,
        }  
    } 
}  
  
impl Mul<Complex> for Complex {
    type Output = Complex;  
  
    fn mul(self, other: Complex) -> Complex {  
        let real = self.real * other.real - self.imag * other.imag;
        let imag = self.real * other.imag + self.imag * other.real;
        Complex { real, imag }  
    }  
}

impl Div<Complex> for Complex {
    type Output = Complex;
  
    fn div(self, other: Complex) -> Complex {
        let real = (self.real * other.real + self.imag * other.imag) / (other.real * other.real + other.imag * other.imag);
        let imag = (self.imag * other.real - self.real * other.imag) / (other.real * other.real + other.imag * other.imag);
        Complex { real, imag }
    }
}  
  
impl Neg for Complex {
    type Output = Complex;
  
    fn neg(self) -> Complex {
        Complex {
            real: -self.real,
            imag: -self.imag,
        }
    }
}

fn main() {
    let z1 = Complex::new(2.0, 3.0);
    let z2 = Complex::new(3.0, 4.0);
    let z3 = Complex::new(3.0, -4.0);

    // 复数的四则运算
    let complex_add = z1.clone() + z2.clone();
    println!("{} + {} = {}", z1, z2, complex_add);

    let z = Complex::new(1.5, 0.5);
    println!("{} + {} = {}", z, z, z.clone() + z.clone());

    let complex_sub = z1.clone() - z2.clone();
    println!("{} - {} = {}", z1, z2, complex_sub);

    let complex_sub = z1.clone() - z1.clone();
    println!("{} - {} = {}", z1, z1, complex_sub);

    let complex_mul = z1.clone() * z2.clone();
    println!("{} * {} = {}", z1, z2, complex_mul);

    let complex_mul = z2.clone() * z3.clone();
    println!("{} * {} = {}", z2, z3, complex_mul);

    let complex_div = z2.clone() / z3.clone();
    println!("{} / {} = {}", z1, z2, complex_div);

    let complex_div = Complex::new(1.0,0.0) / z2.clone();
    println!("1 / {} = {}", z2, complex_div);

    // 对比两个复数是否相等
    println!("{:?}", z1 == z2);
    // 共轭复数
    println!("{:?}", z2 == z3.conj());
    // 复数的相反数
    println!("{:?}", z2 == -z3.clone() + Complex::new(6.0,0.0));

    // 复数的模
    println!("{}", z1.abs());
    println!("{}", z2.abs());
    println!("{}", abs(z3));
}

输出:

(2 + 3i) + (3 + 4i) = (5 + 7i)
(1.5 + 0.5i) + (1.5 + 0.5i) = (3 + i)
(2 + 3i) - (3 + 4i) = (-1 - i)
(2 + 3i) - (2 + 3i) = 0
(2 + 3i) * (3 + 4i) = (-6 + 17i)
(3 + 4i) * (3 - 4i) = 25
(2 + 3i) / (3 + 4i) = (-0.28 + 0.96i)
1 / (3 + 4i) = (0.12 - 0.16i)
false
true
true
3.605551275463989
5
5


小结

如此,复数的四则运算基本都实现了,当然复数还有三角表示式和指数表示式,根据它们的数学定义写出相当代码应该不是很难。有了复数三角式,就能方便地定义出复数的开方运算,有空可以写写这方面的代码。

本文完

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/73746.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Java8函数式编程

ISBN: 978-7-115-38488-1 作者&#xff1a;【英】Richard Warburton 页数&#xff1a;132页 阅读时间&#xff1a;2023-08-05 推荐指数&#xff1a;★★★★★ 练习项目&#xff1a;https://github.com/RichardWarburton/java-8-lambdas-exercises 虽然这本书出版于2014年&…

前端食堂技术周刊第 93 期:7 月登陆 Web 平台的新功能、Node.js 工具箱、Nuxt3 开发技巧、MF 重构方案

美味值&#xff1a;&#x1f31f;&#x1f31f;&#x1f31f;&#x1f31f;&#x1f31f; 口味&#xff1a;橙橙冰萃美式 食堂技术周刊仓库地址&#xff1a;https://github.com/Geekhyt/weekly 大家好&#xff0c;我是童欧巴。欢迎来到前端食堂技术周刊&#xff0c;我们先来…

SQLyog中导入CSV文件入库到MySQL中

1.在数据库中新建一个表&#xff0c;设置列名&#xff08;与待导入文件一致&#xff09;&#xff0c;字段可以多出几个都可以 2.右键表名&#xff0c;导入- - >导入使用本地加载的CSV数据 选择使用加载本地CVS数据 3.指定好转义字符&#xff0c;将终止设置为,号(英文状态下…

2023牛客暑期多校训练营9-Non-Puzzle: Segment Pair

2023牛客暑期多校训练营9-Non-Puzzle: Segment Pair https://ac.nowcoder.com/acm/contest/57363/I 文章目录 2023牛客暑期多校训练营9-Non-Puzzle: Segment Pair题目大意解题思路代码 题目大意 解题思路 对于每一对 [ l i , r i ] [l_i,r_i] [li​,ri​]和 [ l i ′ , r i …

cmake-ibmtpm1682编译

1、error Ossl library is using different radix 异常解决 RADIX_BITS由 64改成32 --whole-archive CMakeFiles\ibm-tpm-my.dir/objects.a -Wl, --no-whole-archive CMakeFiles\ibm-tpm-my.dir\linklibs.rsp CMake中的 --whole-archive以及–no-whole-archive两者都是编译器…

AppStream下载元数据失败

错误&#xff1a;为仓库 AppStream 下载元数据失败 : Cannot prepare internal mirrorlist: No URLs in mirrorlist 目录 一、域名解析 二、CentOS-AppStream.repo 三、CentOS-Base.repo 四、CentOS-Extras.repo 五、rpm更新 一、域名解析 先验证 ping www.baidu.com 不…

基于C#UI Automation自动化测试

步骤 UI Automation 只适用于&#xff0c;标准的win32和 WPF程序 需要添加对UIAutomationClient、 UIAutomationProvider、 UIAutomationTypes的引用 代码 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.D…

【ARM 调试】如何从 crash 信息找出问题原因

一、问题背景 粉丝在进行 ARM-A 系列软件编程时遇到以下问题&#xff0c;串口打印这段日志后就重启了&#xff0c;粉丝求助问是什么原因&#xff1f; Unhandled Exception in EL3. x30 0x0000000000b99b84 x0 0x00000000179a25b0 x1 …

Prometheus技术文档-基本使用-配置文件全解!!!!!

简介&#xff1a; Prometheus是一个开源的系统监控和告警系统&#xff0c;由Google的BorgMon监控系统发展而来。它主要用于监控和度量各种时间序列数据&#xff0c;比如系统性能、网络延迟、应用程序错误等。Prometheus通过采集监控数据并存储在时间序列数据库中&#xff0c;…

【apifox】如何写一份合格的 API 文档?

要想弄清楚如何开始写出一份合格的 API 文档&#xff0c;我们需要首先了解什么是 API&#xff0c;它的使用场景有哪些&#xff0c;应该具备什么样的能力。 什么是 API&#xff1f; 想象一下&#xff0c;当小 A 购入了一台新的电脑后&#xff0c;希望将显示画面投射至一块色准…

对比学习论文综述总结

第一阶段:百花齐放(18-19中) 有InstDisc(Instance Discrimination)、CPC、CMC代表工作。在这个阶段方法模型都还没有统一,目标函数也没有统一,代理任务也没有统一,所以说是一个百花齐放的时代 1 判别式代理任务---个体判别任务 1.1 Inst Dict---一个编码器+一个memory…

Redis_主从复制

8. 主从复制 8.1 简介 主从库采用读写分离的方式 读操作&#xff1a;主库、从库都可以处理写操作&#xff1a;首先写到主库执行&#xff0c;然后再将主库同步给从库。 实现读写分离&#xff0c;性能扩展 容灾快速恢复 8.2 主从复制步骤 创建一个目录 ,在root下创建一个m…

2009年下半年 软件设计师 上午试卷

博主介绍&#xff1a;✌全网粉丝3W&#xff0c;全栈开发工程师&#xff0c;从事多年软件开发&#xff0c;在大厂呆过。持有软件中级、六级等证书。可提供微服务项目搭建与毕业项目实战&#xff0c;博主也曾写过优秀论文&#xff0c;查重率极低&#xff0c;在这方面有丰富的经验…

RedisDesktopManage

RDM 简介下载安装 简介 RedisDesktopManager&#xff08;RDM&#xff09;是一个开源的跨平台图形界面工具&#xff0c;用于管理和操作 Redis 数据库。它提供了一个用户友好的界面&#xff0c;使用户能够轻松地连接、浏览、查询和修改 Redis 数据&#xff0c;而无需使用命令行界…

ubuntu部署haproxy

HAProxy是可提供高可用性、负载均衡以及基于TCP和HTTP应用的代理. 1、更新系统报 通过在终端中运行以下命令,确保所有系统包都是最新的 sudo apt updatesudo apt upgrade 2、安装Haproxy sudo apt install haproxy 设置开机自动启动haproxy服务 sudo systemctl enable h…

都说go协程性能好,这次我们来试试java协程

java 协程原理 在Java中&#xff0c;协程&#xff08;Coroutine&#xff09;是一种轻量级的线程解决方案&#xff0c;它可以在代码中实现类似于多线程的并发操作&#xff0c;但不涉及线程的创建和切换开销。 在传统的Java多线程编程模型中&#xff0c;线程的切换开销较大&…

0142 存储系统2

目录 3.存储系统 3.4外部存储器 3.5高速缓冲存储器 3.6虚拟存储器 部分习题 3.存储系统 3.4外部存储器 3.5高速缓冲存储器 3.6虚拟存储器 部分习题 1.一个磁盘转速为7200转/分&#xff0c;每个磁道有160个扇区&#xff0c;每个扇区有512字节&#xff0c;则在理想情况下&…

SQL | 使用函数处理数据

8-使用函数处理数据 8.1-函数 SQL可以用函数来处理数据。函数一般是在数据上执行的&#xff0c;为数据的转换和处理提供了方便。 8.1.1 函数带来的问题 每种DBMS都有特定的函数&#xff0c;只有很少一部分函数&#xff0c;是被所有主要的DBMS等同的支持。 虽然所有的类型的…

YOLO相关原理(文件结构、视频检测等)

超参数进化(hyperparameter evolution) 超参数进化是一种使用了genetic algorithm&#xff08;GA&#xff09;遗传算法进行超参数优化的一种方法。 YOLOv5的文件结构 images文件夹内的文件和labels中的文件存在一一对应关系 激活函数&#xff1a;非线性处理单元 activation f…

使用Python和pyodbc库将文件信息插入Access数据库

将文件信息插入 Access 数据库的博客文章示例&#xff1a; 简介&#xff1a; 在日常编程工作中&#xff0c;我们经常需要处理文件和文件夹。有时&#xff0c;我们需要遍历文件夹中的所有文件&#xff0c;并将文件的路径、类型、文件名以及修改日期和创建日期等信息保存到数据库…
最新文章