国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Rust 重載運算符|復數(shù)結構的“加減乘除”四則運算

這篇具有很好參考價值的文章主要介紹了Rust 重載運算符|復數(shù)結構的“加減乘除”四則運算。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

Rust 重載運算符|復數(shù)結構的“加減乘除”四則運算,Rust,算法,rust

復數(shù)

基本概念

復數(shù)定義

由實數(shù)部分和虛數(shù)部分所組成的數(shù),形如a+bi 。

其中a、b為實數(shù),i 為“虛數(shù)單位”,i2 = -1,即虛數(shù)單位的平方等于-1。

a、b分別叫做復數(shù)a+bi的實部和虛部。

當b=0時,a+bi=a 為實數(shù);
當b≠0時,a+bi 又稱虛數(shù);
當b≠0、a=0時,bi 稱為純虛數(shù)。

實數(shù)和虛數(shù)都是復數(shù)的子集。如同實數(shù)可以在數(shù)軸上表示一樣復數(shù)也可以在平面上表示,復數(shù)x+yi以坐標點(x,y)來表示。表示復數(shù)的平面稱為“復平面”。

復數(shù)相等

兩個復數(shù)不能比較大小,但當個兩個復數(shù)的實部和虛部分別相等時,即表示兩個復數(shù)相等。

共軛復數(shù)

如果兩個復數(shù)的實部相等,虛部互為相反數(shù),那么這兩個復數(shù)互為共軛復數(shù)。

復數(shù)的模

復數(shù)的實部與虛部的平方和的正的平方根的值稱為該復數(shù)的模,數(shù)學上用與絕對值“|z|”相同的符號來表示。雖然從定義上是不相同的,但兩者的物理意思都表示“到原點的距離”。

復數(shù)的四則運算

加法(減法)法則

復數(shù)的加法法則:設z1=a+bi,z2 =c+di是任意兩個復數(shù)。兩者和的實部是原來兩個復數(shù)實部的和,它的虛部是原來兩個虛部的和。兩個復數(shù)的和依然是復數(shù)。

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

乘法法則

復數(shù)的乘法法則:把兩個復數(shù)相乘,類似兩個多項式相乘,結果中i2=-1,把實部與虛部分別合并。兩個復數(shù)的積仍然是一個復數(shù)。

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

除法法則

復數(shù)除法法則:滿足(c+di)(x+yi)=(a+bi)的復數(shù)x+yi(x,y∈R)叫復數(shù)a+bi除以復數(shù)c+di的商。

運算方法:可以把除法換算成乘法做,將分子分母同時乘上分母的共軛復數(shù),再用乘法運算。

即(a+bi)/(c+di)=(a+bi)(c-di)/(c*c+d*d)=[(ac+bd)+(bc-ad)i]/(c*c+d*d)

復數(shù)的Rust代碼實現(xiàn)

結構定義

Rust語言中,沒有像python一樣內(nèi)置complex復數(shù)數(shù)據(jù)類型,我們可以用兩個浮點數(shù)分別表示復數(shù)的實部和虛部,自定義一個結構數(shù)據(jù)類型,表示如下:

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)] 自動定義了復數(shù)結構的輸出格式,如以上代碼輸出如下:

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

重載四則運算

復數(shù)數(shù)據(jù)結構不能直接用加減乘除來做復數(shù)運算,需要導入標準庫ops的運算符:

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

Add, Sub, Mul, Div, Neg 分別表示加減乘除以及相反數(shù),類似C++或者python語言中“重載運算符”的概念。

根據(jù)復數(shù)的運算法則,寫出對應代碼:

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);

    // 復數(shù)的四則運算
    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);

    // 對比兩個復數(shù)是否相等
    println!("{:?}", z1 == z2);
    // 共軛復數(shù)
    println!("{:?}", z2 == z3.conj());
    // 復數(shù)的相反數(shù)
    println!("{:?}", z2 == -z3.clone() + Complex::new(6.0,0.0));

    // 復數(shù)的模
    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

示例代碼中,同時還定義了復數(shù)的模 abs(),共軛復數(shù) conj()。

兩個復數(shù)的相等比較 z1 == z2,需要?#[derive(PartialEq)] 支持。

自定義 trait Display

復數(shù)結構的原始 Debug trait 表達的輸出格式比較繁復,如:

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

想要輸出和數(shù)學中相同的表達(如 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,正數(shù)和負數(shù)。另外當虛部絕對值為1時省略1僅輸出i虛數(shù)單位。

完整代碼如下:

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);

    // 復數(shù)的四則運算
    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);

    // 對比兩個復數(shù)是否相等
    println!("{:?}", z1 == z2);
    // 共軛復數(shù)
    println!("{:?}", z2 == z3.conj());
    // 復數(shù)的相反數(shù)
    println!("{:?}", z2 == -z3.clone() + Complex::new(6.0,0.0));

    // 復數(shù)的模
    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


小結

如此,復數(shù)的四則運算基本都實現(xiàn)了,當然復數(shù)還有三角表示式和指數(shù)表示式,根據(jù)它們的數(shù)學定義寫出相當代碼應該不是很難。有了復數(shù)三角式,就能方便地定義出復數(shù)的開方運算,有空可以寫寫這方面的代碼。

本文完文章來源地址http://www.zghlxwxcb.cn/news/detail-648762.html

到了這里,關于Rust 重載運算符|復數(shù)結構的“加減乘除”四則運算的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • 插入運算符“>>“和提取運算符“<<“的重載

    ??博主主頁: @??. 一懷明月?? ????? 專欄系列: 線性代數(shù),C初學者入門訓練,題解C,C的使用文章,「初學」C++ ?? 座右銘: “不要等到什么都沒有了,才下定決心去做” ??????大家覺不錯的話,就懇求大家點點關注,點點小愛心,指點指點?????? 目錄 ??插

    2024年02月07日
    瀏覽(26)
  • 運算符重載和重載函數(shù)

    1.運算符重載的意義 C++為了增強代碼的可讀性引入了運算符重載,運算符重載是具有特殊函數(shù)名的函數(shù),也具有其返回值類型,函數(shù)名字以及參數(shù)列表,其返回值類型與參數(shù)列表與普通的函數(shù)類似。 函數(shù)名字為:operator后面接需要重載的運算符符號。 函數(shù)原型:返回值

    2024年02月06日
    瀏覽(19)
  • C++——類和對象3|日期類型|Cout運算符重載|Cin運算符重載|const成員|

    C++——類和對象3|日期類型|Cout運算符重載|Cin運算符重載|const成員|

    目錄 日期類型? Date.h? Date.cpp? Test.cpp? 實現(xiàn)Cout運算符重載? 實現(xiàn)Cin運算符重載? 根據(jù)日期算星期? 修改后完整代碼?? Date.h? Date.cpp? const成員 ?取地址及const取地址操作符重載 習題? 計算日期到天數(shù)轉(zhuǎn)換? ? ?一個類到底可以重載哪些運算符,要看哪些運算符對這個類型有

    2023年04月13日
    瀏覽(27)
  • 【C++】運算符重載 ⑩ ( 下標 [] 運算符重載 | 函數(shù)原型 int& operator[](int i) | 完整代碼示例 )

    【C++】運算符重載 ⑩ ( 下標 [] 運算符重載 | 函數(shù)原型 int& operator[](int i) | 完整代碼示例 )

    在之前的博客 【C++】面向?qū)ο笫纠?- 數(shù)組類 ( 示例需求 | 創(chuàng)建封裝類 | 數(shù)組類頭文件 Array.h | 數(shù)組類實現(xiàn) Array.cpp | 測試類 Test.cpp - 主函數(shù)入口 ) 中 , 實現(xiàn)了一個數(shù)組類 , 在一個類中 , 封裝了一個 int 類型的指針 , 該指針指向堆內(nèi)存的 內(nèi)存空間 , 用于存放一個數(shù)組 ; 核心是 2

    2024年02月07日
    瀏覽(30)
  • C++修煉之筑基期第四層 ——透過日期類看運算符重載 | 賦值運算符重載 | 取地址操作符重載

    C++修煉之筑基期第四層 ——透過日期類看運算符重載 | 賦值運算符重載 | 取地址操作符重載

    ??作者簡介: 花想云 ,在讀本科生一枚,致力于 C/C++、Linux 學習。 ?? 本文收錄于 C++系列 ,本專欄主要內(nèi)容為 C++ 初階、C++ 進階、STL 詳解等,專為大學生打造全套 C++ 學習教程,持續(xù)更新! ?? 相關專欄推薦: C語言初階系列 、 C語言進階系列 、 數(shù)據(jù)結構與算法 本章主要

    2023年04月09日
    瀏覽(21)
  • 【C++】運算符重載

    目錄 1. 基本概念 1.1 直接調(diào)用一個重載的運算符函數(shù) 1.2 某些運算符不應該被重載 1.3 使用與內(nèi)置類型一致的含義 1.4 賦值和復合賦值運算符 1.5 選擇作為成員或者非成員 2. 輸入和輸出運算符 2.1 輸出運算符重載 2.2 輸入運算符重載 3. 算術和關系運算符 3.1 算數(shù)運算符重載 3.2

    2024年02月11日
    瀏覽(32)
  • C++——運算符重載

    C++——運算符重載

    運算符重載,就是對已有的運算符重新進行定義,賦予其另一種功能,以適應不同的數(shù)據(jù)類型。 運算符重載的目的是讓語法更加簡潔 運算符重載不能改變本來寓意,不能改變基礎類型寓意 運算符重載的本質(zhì)是另一種函數(shù)調(diào)用(是編譯器去調(diào)用) 這個函數(shù)統(tǒng)一的名字叫opera

    2024年02月16日
    瀏覽(34)
  • C++:重載運算符

    C++:重載運算符

    1.重載不能改變運算符運算的對象個數(shù) 2.重載不能改變運算符的優(yōu)先級別 3.重載不能改變運算符的結合性 4.重載運算符必須和用戶定義的自定義類型的對象一起使用,其參數(shù)至少應該有一個是類對象,或類對象的引用 5.重載運算符的功能要類似于該運算符作用于標準類型數(shù)據(jù)

    2024年02月10日
    瀏覽(20)
  • kotlin 運算符重載解析

    反編譯之后的java代碼為: 可以看到實際是生成了一個 plus方法, 然后我們把我們的plus1方法名稱修改為plus ,編譯報錯,提示有2個同名方法。 完美 。

    2024年02月15日
    瀏覽(20)
  • 復習 --- C++運算符重載

    .5 運算符重載 運算符重載概念:對已有的運算符重新進行定義,賦予其另外一種功能,以適應不同的數(shù)據(jù)類型 4.5.1 加號運算符重載 作用:實現(xiàn)兩個自定義數(shù)據(jù)類型相加的運算 4.5.2 左移運算符重載 4.5.3遞增運算符重載 作用:通過重載遞增運算符,實現(xiàn)自己的整型數(shù)據(jù) 4.5.4 賦

    2024年02月07日
    瀏覽(26)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包