更新libclamav库1.0.0版本

This commit is contained in:
2023-01-14 18:28:39 +08:00
parent b879ee0b2e
commit 45fe15f472
8531 changed files with 1222046 additions and 177272 deletions

View File

@@ -0,0 +1 @@
{"files":{"Cargo.toml":"190fed1a9ab0086191fe1d6fd0cc4825e36cb58a6189a97670fc5fd3a15c9a0c","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"fa93b9b268ee49bcecd3aba356fce28262417153b7327a3a947ebabf6552708b","RELEASES.md":"d3c10542bce11375540970e823847408bc3c5b4d7ab4a06102656d9d7e050aba","src/cast.rs":"8206bcfb99b712340383332fb760dba9cee4be8c994bd9a38d0b8c6e6bc5f7b1","src/complex_float.rs":"006a4331feac2d747fef2928b4af7dc3b892e55749313f73c0396a2107339edb","src/crand.rs":"d92d8227b5b02186abc81ca8153be404a9ef0a5273deefec921d2d7f74bf6a66","src/lib.rs":"0d5e277779700dc571e8d355075da847e51d782f14a42ea96c6289cee0643344","src/pow.rs":"974fd585da8c2b7ac3f68e93a3881c56a3f0f3e506009fb3d862c6000064abb7"},"package":"7ae39348c8bc5fbd7f40c727a9925f03517afd2ab27d46702108b6a7e5414c19"}

View File

@@ -0,0 +1,69 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2018"
name = "num-complex"
version = "0.4.2"
authors = ["The Rust Project Developers"]
exclude = [
"/bors.toml",
"/ci/*",
"/.github/*",
]
description = "Complex numbers implementation for Rust"
homepage = "https://github.com/rust-num/num-complex"
documentation = "https://docs.rs/num-complex"
readme = "README.md"
keywords = [
"mathematics",
"numerics",
]
categories = [
"algorithms",
"data-structures",
"science",
"no-std",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/rust-num/num-complex"
[package.metadata.docs.rs]
features = [
"bytemuck",
"std",
"serde",
"rand",
]
[dependencies.bytemuck]
version = "1"
optional = true
[dependencies.num-traits]
version = "0.2.11"
features = ["i128"]
default-features = false
[dependencies.rand]
version = "0.8"
optional = true
default-features = false
[dependencies.serde]
version = "1.0"
optional = true
default-features = false
[features]
default = ["std"]
libm = ["num-traits/libm"]
std = ["num-traits/std"]

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,25 @@
Copyright (c) 2014 The Rust Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,55 @@
# num-complex
[![crate](https://img.shields.io/crates/v/num-complex.svg)](https://crates.io/crates/num-complex)
[![documentation](https://docs.rs/num-complex/badge.svg)](https://docs.rs/num-complex)
[![minimum rustc 1.31](https://img.shields.io/badge/rustc-1.31+-red.svg)](https://rust-lang.github.io/rfcs/2495-min-rust-version.html)
[![build status](https://github.com/rust-num/num-complex/workflows/master/badge.svg)](https://github.com/rust-num/num-complex/actions)
`Complex` numbers for Rust.
## Usage
Add this to your `Cargo.toml`:
```toml
[dependencies]
num-complex = "0.4"
```
## Features
This crate can be used without the standard library (`#![no_std]`) by disabling
the default `std` feature. Use this in `Cargo.toml`:
```toml
[dependencies.num-complex]
version = "0.4"
default-features = false
```
Features based on `Float` types are only available when `std` or `libm` is
enabled. Where possible, `FloatCore` is used instead. Formatting complex
numbers only supports format width when `std` is enabled.
## Releases
Release notes are available in [RELEASES.md](RELEASES.md).
## Compatibility
The `num-complex` crate is tested for rustc 1.31 and greater.
## License
Licensed under either of
* [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)
* [MIT license](http://opensource.org/licenses/MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.

View File

@@ -0,0 +1,161 @@
# Release 0.4.2 (2022-06-17)
- [The new `ComplexFloat` trait][95] provides a generic abstraction between
floating-point `T` and `Complex<T>`.
- [`Complex::exp` now handles edge cases with NaN and infinite parts][104].
**Contributors**: @cuviper, @JorisDeRidder, @obsgolem, @YakoYakoYokuYoku
[95]: https://github.com/rust-num/num-complex/pull/95
[104]: https://github.com/rust-num/num-complex/pull/104
# Release 0.4.1 (2022-04-29)
- [`Complex::from_str_radix` now returns an error for radix > 18][90], because
'i' and 'j' as digits are ambiguous with _i_ or _j_ imaginary parts.
- [`Complex<T>` now implements `bytemuck` traits when `T` does][100].
- [`Complex::cis` creates a complex with the given phase][101], _e_<sup>_i_ θ</sup>.
**Contributors**: @bluss, @bradleyharden, @cuviper, @rayhem
[90]: https://github.com/rust-num/num-complex/pull/90
[100]: https://github.com/rust-num/num-complex/pull/100
[101]: https://github.com/rust-num/num-complex/pull/101
# Release 0.4.0 (2021-03-05)
- `rand` support has been updated to 0.8, requiring Rust 1.36.
**Contributors**: @cuviper
# Release 0.3.1 (2020-10-29)
- Clarify the license specification as "MIT OR Apache-2.0".
**Contributors**: @cuviper
# Release 0.3.0 (2020-06-13)
### Enhancements
- [The new "libm" feature passes through to `num-traits`][73], enabling `Float`
features on no-`std` builds.
### Breaking Changes
- `num-complex` now requires Rust 1.31 or greater.
- The "i128" opt-in feature was removed, now always available.
- [Updated public dependences][65]:
- `rand` support has been updated to 0.7, requiring Rust 1.32.
- [Methods for `T: Float` now take values instead of references][82], most
notably affecting the constructor `from_polar`.
**Contributors**: @cuviper, @SOF3, @vks
[65]: https://github.com/rust-num/num-complex/pull/65
[73]: https://github.com/rust-num/num-complex/pull/73
[82]: https://github.com/rust-num/num-complex/pull/82
# Release 0.2.4 (2020-01-09)
- [`Complex::new` is now a `const fn` for Rust 1.31 and later][63].
- [Updated the `autocfg` build dependency to 1.0][68].
**Contributors**: @burrbull, @cuviper, @dingelish
[63]: https://github.com/rust-num/num-complex/pull/63
[68]: https://github.com/rust-num/num-complex/pull/68
# Release 0.2.3 (2019-06-11)
- [`Complex::sqrt()` is now more accurate for negative reals][60].
- [`Complex::cbrt()` computes the principal cube root][61].
**Contributors**: @cuviper
[60]: https://github.com/rust-num/num-complex/pull/60
[61]: https://github.com/rust-num/num-complex/pull/61
# Release 0.2.2 (2019-06-10)
- [`Complex::l1_norm()` computes the Manhattan distance from the origin][43].
- [`Complex::fdiv()` and `finv()` use floating-point for inversion][41], which
may avoid overflows for some inputs, at the cost of trigonometric rounding.
- [`Complex` now implements `num_traits::MulAdd` and `MulAddAssign`][44].
- [`Complex` now implements `Zero::set_zero` and `One::set_one`][57].
- [`Complex` now implements `num_traits::Pow` and adds `powi` and `powu`][56].
**Contributors**: @adamnemecek, @cuviper, @ignatenkobrain, @Schultzer
[41]: https://github.com/rust-num/num-complex/pull/41
[43]: https://github.com/rust-num/num-complex/pull/43
[44]: https://github.com/rust-num/num-complex/pull/44
[56]: https://github.com/rust-num/num-complex/pull/56
[57]: https://github.com/rust-num/num-complex/pull/57
# Release 0.2.1 (2018-10-08)
- [`Complex` now implements `ToPrimitive`, `FromPrimitive`, `AsPrimitive`, and `NumCast`][33].
**Contributors**: @cuviper, @termoshtt
[33]: https://github.com/rust-num/num-complex/pull/33
# Release 0.2.0 (2018-05-24)
### Enhancements
- [`Complex` now implements `num_traits::Inv` and `One::is_one`][17].
- [`Complex` now implements `Sum` and `Product`][11].
- [`Complex` now supports `i128` and `u128` components][27] with Rust 1.26+.
- [`Complex` now optionally supports `rand` 0.5][28], implementing the
`Standard` distribution and [a generic `ComplexDistribution`][30].
- [`Rem` with a scalar divisor now avoids `norm_sqr` overflow][25].
### Breaking Changes
- [`num-complex` now requires rustc 1.15 or greater][16].
- [There is now a `std` feature][22], enabled by default, along with the
implication that building *without* this feature makes this a `#![no_std]`
crate. A few methods now require `FloatCore`, and the remaining methods
based on `Float` are only supported with `std`.
- [The `serde` dependency has been updated to 1.0][7], and `rustc-serialize`
is no longer supported by `num-complex`.
**Contributors**: @clarcharr, @cuviper, @shingtaklam1324, @termoshtt
[7]: https://github.com/rust-num/num-complex/pull/7
[11]: https://github.com/rust-num/num-complex/pull/11
[16]: https://github.com/rust-num/num-complex/pull/16
[17]: https://github.com/rust-num/num-complex/pull/17
[22]: https://github.com/rust-num/num-complex/pull/22
[25]: https://github.com/rust-num/num-complex/pull/25
[27]: https://github.com/rust-num/num-complex/pull/27
[28]: https://github.com/rust-num/num-complex/pull/28
[30]: https://github.com/rust-num/num-complex/pull/30
# Release 0.1.43 (2018-03-08)
- [Fix a usage typo in README.md][20].
**Contributors**: @shingtaklam1324
[20]: https://github.com/rust-num/num-complex/pull/20
# Release 0.1.42 (2018-02-07)
- [num-complex now has its own source repository][num-356] at [rust-num/num-complex][home].
**Contributors**: @cuviper
[home]: https://github.com/rust-num/num-complex
[num-356]: https://github.com/rust-num/num/pull/356
# Prior releases
No prior release notes were kept. Thanks all the same to the many
contributors that have made this crate what it is!

View File

@@ -0,0 +1,119 @@
use super::Complex;
use num_traits::{AsPrimitive, FromPrimitive, Num, NumCast, ToPrimitive};
macro_rules! impl_to_primitive {
($ty:ty, $to:ident) => {
#[inline]
fn $to(&self) -> Option<$ty> {
if self.im.is_zero() {
self.re.$to()
} else {
None
}
}
};
} // impl_to_primitive
// Returns None if Complex part is non-zero
impl<T: ToPrimitive + Num> ToPrimitive for Complex<T> {
impl_to_primitive!(usize, to_usize);
impl_to_primitive!(isize, to_isize);
impl_to_primitive!(u8, to_u8);
impl_to_primitive!(u16, to_u16);
impl_to_primitive!(u32, to_u32);
impl_to_primitive!(u64, to_u64);
impl_to_primitive!(i8, to_i8);
impl_to_primitive!(i16, to_i16);
impl_to_primitive!(i32, to_i32);
impl_to_primitive!(i64, to_i64);
impl_to_primitive!(u128, to_u128);
impl_to_primitive!(i128, to_i128);
impl_to_primitive!(f32, to_f32);
impl_to_primitive!(f64, to_f64);
}
macro_rules! impl_from_primitive {
($ty:ty, $from_xx:ident) => {
#[inline]
fn $from_xx(n: $ty) -> Option<Self> {
Some(Complex {
re: T::$from_xx(n)?,
im: T::zero(),
})
}
};
} // impl_from_primitive
impl<T: FromPrimitive + Num> FromPrimitive for Complex<T> {
impl_from_primitive!(usize, from_usize);
impl_from_primitive!(isize, from_isize);
impl_from_primitive!(u8, from_u8);
impl_from_primitive!(u16, from_u16);
impl_from_primitive!(u32, from_u32);
impl_from_primitive!(u64, from_u64);
impl_from_primitive!(i8, from_i8);
impl_from_primitive!(i16, from_i16);
impl_from_primitive!(i32, from_i32);
impl_from_primitive!(i64, from_i64);
impl_from_primitive!(u128, from_u128);
impl_from_primitive!(i128, from_i128);
impl_from_primitive!(f32, from_f32);
impl_from_primitive!(f64, from_f64);
}
impl<T: NumCast + Num> NumCast for Complex<T> {
fn from<U: ToPrimitive>(n: U) -> Option<Self> {
Some(Complex {
re: T::from(n)?,
im: T::zero(),
})
}
}
impl<T, U> AsPrimitive<U> for Complex<T>
where
T: AsPrimitive<U>,
U: 'static + Copy,
{
fn as_(self) -> U {
self.re.as_()
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_to_primitive() {
let a: Complex<u32> = Complex { re: 3, im: 0 };
assert_eq!(a.to_i32(), Some(3_i32));
let b: Complex<u32> = Complex { re: 3, im: 1 };
assert_eq!(b.to_i32(), None);
let x: Complex<f32> = Complex { re: 1.0, im: 0.1 };
assert_eq!(x.to_f32(), None);
let y: Complex<f32> = Complex { re: 1.0, im: 0.0 };
assert_eq!(y.to_f32(), Some(1.0));
let z: Complex<f32> = Complex { re: 1.0, im: 0.0 };
assert_eq!(z.to_i32(), Some(1));
}
#[test]
fn test_from_primitive() {
let a: Complex<f32> = FromPrimitive::from_i32(2).unwrap();
assert_eq!(a, Complex { re: 2.0, im: 0.0 });
}
#[test]
fn test_num_cast() {
let a: Complex<f32> = NumCast::from(2_i32).unwrap();
assert_eq!(a, Complex { re: 2.0, im: 0.0 });
}
#[test]
fn test_as_primitive() {
let a: Complex<f32> = Complex { re: 2.0, im: 0.2 };
let a_: i32 = a.as_();
assert_eq!(a_, 2_i32);
}
}

View File

@@ -0,0 +1,439 @@
// Keeps us from accidentally creating a recursive impl rather than a real one.
#![deny(unconditional_recursion)]
use core::ops::Neg;
use num_traits::{Float, FloatConst, Num, NumCast};
use crate::Complex;
mod private {
use num_traits::{Float, FloatConst};
use crate::Complex;
pub trait Seal {}
impl<T> Seal for T where T: Float + FloatConst {}
impl<T: Float + FloatConst> Seal for Complex<T> {}
}
/// Generic trait for floating point complex numbers.
///
/// This trait defines methods which are common to complex floating point
/// numbers and regular floating point numbers.
///
/// This trait is sealed to prevent it from being implemented by anything other
/// than floating point scalars and [Complex] floats.
pub trait ComplexFloat: Num + NumCast + Copy + Neg<Output = Self> + private::Seal {
/// The type used to represent the real coefficients of this complex number.
type Real: Float + FloatConst;
/// Returns `true` if this value is `NaN` and false otherwise.
fn is_nan(self) -> bool;
/// Returns `true` if this value is positive infinity or negative infinity and
/// false otherwise.
fn is_infinite(self) -> bool;
/// Returns `true` if this number is neither infinite nor `NaN`.
fn is_finite(self) -> bool;
/// Returns `true` if the number is neither zero, infinite,
/// [subnormal](http://en.wikipedia.org/wiki/Denormal_number), or `NaN`.
fn is_normal(self) -> bool;
/// Take the reciprocal (inverse) of a number, `1/x`. See also [Complex::finv].
fn recip(self) -> Self;
/// Raises `self` to a signed integer power.
fn powi(self, exp: i32) -> Self;
/// Raises `self` to a real power.
fn powf(self, exp: Self::Real) -> Self;
/// Raises `self` to a complex power.
fn powc(self, exp: Complex<Self::Real>) -> Complex<Self::Real>;
/// Take the square root of a number.
fn sqrt(self) -> Self;
/// Returns `e^(self)`, (the exponential function).
fn exp(self) -> Self;
/// Returns `2^(self)`.
fn exp2(self) -> Self;
/// Returns `base^(self)`.
fn expf(self, base: Self::Real) -> Self;
/// Returns the natural logarithm of the number.
fn ln(self) -> Self;
/// Returns the logarithm of the number with respect to an arbitrary base.
fn log(self, base: Self::Real) -> Self;
/// Returns the base 2 logarithm of the number.
fn log2(self) -> Self;
/// Returns the base 10 logarithm of the number.
fn log10(self) -> Self;
/// Take the cubic root of a number.
fn cbrt(self) -> Self;
/// Computes the sine of a number (in radians).
fn sin(self) -> Self;
/// Computes the cosine of a number (in radians).
fn cos(self) -> Self;
/// Computes the tangent of a number (in radians).
fn tan(self) -> Self;
/// Computes the arcsine of a number. Return value is in radians in
/// the range [-pi/2, pi/2] or NaN if the number is outside the range
/// [-1, 1].
fn asin(self) -> Self;
/// Computes the arccosine of a number. Return value is in radians in
/// the range [0, pi] or NaN if the number is outside the range
/// [-1, 1].
fn acos(self) -> Self;
/// Computes the arctangent of a number. Return value is in radians in the
/// range [-pi/2, pi/2];
fn atan(self) -> Self;
/// Hyperbolic sine function.
fn sinh(self) -> Self;
/// Hyperbolic cosine function.
fn cosh(self) -> Self;
/// Hyperbolic tangent function.
fn tanh(self) -> Self;
/// Inverse hyperbolic sine function.
fn asinh(self) -> Self;
/// Inverse hyperbolic cosine function.
fn acosh(self) -> Self;
/// Inverse hyperbolic tangent function.
fn atanh(self) -> Self;
/// Returns the real part of the number.
fn re(self) -> Self::Real;
/// Returns the imaginary part of the number.
fn im(self) -> Self::Real;
/// Returns the absolute value of the number. See also [Complex::norm]
fn abs(self) -> Self::Real;
/// Returns the L1 norm `|re| + |im|` -- the [Manhattan distance] from the origin.
///
/// [Manhattan distance]: https://en.wikipedia.org/wiki/Taxicab_geometry
fn l1_norm(&self) -> Self::Real;
/// Computes the argument of the number.
fn arg(self) -> Self::Real;
/// Computes the complex conjugate of the number.
///
/// Formula: `a+bi -> a-bi`
fn conj(self) -> Self;
}
macro_rules! forward {
($( $base:ident :: $method:ident ( self $( , $arg:ident : $ty:ty )* ) -> $ret:ty ; )*)
=> {$(
#[inline]
fn $method(self $( , $arg : $ty )* ) -> $ret {
$base::$method(self $( , $arg )* )
}
)*};
}
macro_rules! forward_ref {
($( Self :: $method:ident ( & self $( , $arg:ident : $ty:ty )* ) -> $ret:ty ; )*)
=> {$(
#[inline]
fn $method(self $( , $arg : $ty )* ) -> $ret {
Self::$method(&self $( , $arg )* )
}
)*};
}
impl<T> ComplexFloat for T
where
T: Float + FloatConst,
{
type Real = T;
fn re(self) -> Self::Real {
self
}
fn im(self) -> Self::Real {
T::zero()
}
fn l1_norm(&self) -> Self::Real {
self.abs()
}
fn arg(self) -> Self::Real {
if self.is_nan() {
self
} else if self.is_sign_negative() {
T::PI()
} else {
T::zero()
}
}
fn powc(self, exp: Complex<Self::Real>) -> Complex<Self::Real> {
Complex::new(self, T::zero()).powc(exp)
}
fn conj(self) -> Self {
self
}
fn expf(self, base: Self::Real) -> Self {
base.powf(self)
}
forward! {
Float::is_normal(self) -> bool;
Float::is_infinite(self) -> bool;
Float::is_finite(self) -> bool;
Float::is_nan(self) -> bool;
Float::recip(self) -> Self;
Float::powi(self, n: i32) -> Self;
Float::powf(self, f: Self) -> Self;
Float::sqrt(self) -> Self;
Float::cbrt(self) -> Self;
Float::exp(self) -> Self;
Float::exp2(self) -> Self;
Float::ln(self) -> Self;
Float::log(self, base: Self) -> Self;
Float::log2(self) -> Self;
Float::log10(self) -> Self;
Float::sin(self) -> Self;
Float::cos(self) -> Self;
Float::tan(self) -> Self;
Float::asin(self) -> Self;
Float::acos(self) -> Self;
Float::atan(self) -> Self;
Float::sinh(self) -> Self;
Float::cosh(self) -> Self;
Float::tanh(self) -> Self;
Float::asinh(self) -> Self;
Float::acosh(self) -> Self;
Float::atanh(self) -> Self;
Float::abs(self) -> Self;
}
}
impl<T: Float + FloatConst> ComplexFloat for Complex<T> {
type Real = T;
fn re(self) -> Self::Real {
self.re
}
fn im(self) -> Self::Real {
self.im
}
fn abs(self) -> Self::Real {
self.norm()
}
fn recip(self) -> Self {
self.finv()
}
// `Complex::l1_norm` uses `Signed::abs` to let it work
// for integers too, but we can just use `Float::abs`.
fn l1_norm(&self) -> Self::Real {
self.re.abs() + self.im.abs()
}
// `Complex::is_*` methods use `T: FloatCore`, but we
// have `T: Float` that can do them as well.
fn is_nan(self) -> bool {
self.re.is_nan() || self.im.is_nan()
}
fn is_infinite(self) -> bool {
!self.is_nan() && (self.re.is_infinite() || self.im.is_infinite())
}
fn is_finite(self) -> bool {
self.re.is_finite() && self.im.is_finite()
}
fn is_normal(self) -> bool {
self.re.is_normal() && self.im.is_normal()
}
forward! {
Complex::arg(self) -> Self::Real;
Complex::powc(self, exp: Complex<Self::Real>) -> Complex<Self::Real>;
Complex::exp2(self) -> Self;
Complex::log(self, base: Self::Real) -> Self;
Complex::log2(self) -> Self;
Complex::log10(self) -> Self;
Complex::powf(self, f: Self::Real) -> Self;
Complex::sqrt(self) -> Self;
Complex::cbrt(self) -> Self;
Complex::exp(self) -> Self;
Complex::expf(self, base: Self::Real) -> Self;
Complex::ln(self) -> Self;
Complex::sin(self) -> Self;
Complex::cos(self) -> Self;
Complex::tan(self) -> Self;
Complex::asin(self) -> Self;
Complex::acos(self) -> Self;
Complex::atan(self) -> Self;
Complex::sinh(self) -> Self;
Complex::cosh(self) -> Self;
Complex::tanh(self) -> Self;
Complex::asinh(self) -> Self;
Complex::acosh(self) -> Self;
Complex::atanh(self) -> Self;
}
forward_ref! {
Self::powi(&self, n: i32) -> Self;
Self::conj(&self) -> Self;
}
}
#[cfg(test)]
mod test {
use crate::{
complex_float::ComplexFloat,
test::{_0_0i, _0_1i, _1_0i, _1_1i, float::close},
Complex,
};
use std::f64; // for constants before Rust 1.43.
fn closef(a: f64, b: f64) -> bool {
close_to_tolf(a, b, 1e-10)
}
fn close_to_tolf(a: f64, b: f64, tol: f64) -> bool {
// returns true if a and b are reasonably close
let close = (a == b) || (a - b).abs() < tol;
if !close {
println!("{:?} != {:?}", a, b);
}
close
}
#[test]
fn test_exp2() {
assert!(close(ComplexFloat::exp2(_0_0i), _1_0i));
assert!(closef(<f64 as ComplexFloat>::exp2(0.), 1.));
}
#[test]
fn test_exp() {
assert!(close(ComplexFloat::exp(_0_0i), _1_0i));
assert!(closef(ComplexFloat::exp(0.), 1.));
}
#[test]
fn test_powi() {
assert!(close(ComplexFloat::powi(_0_1i, 4), _1_0i));
assert!(closef(ComplexFloat::powi(-1., 4), 1.));
}
#[test]
fn test_powz() {
assert!(close(ComplexFloat::powc(_1_0i, _0_1i), _1_0i));
assert!(close(ComplexFloat::powc(1., _0_1i), _1_0i));
}
#[test]
fn test_log2() {
assert!(close(ComplexFloat::log2(_1_0i), _0_0i));
assert!(closef(ComplexFloat::log2(1.), 0.));
}
#[test]
fn test_log10() {
assert!(close(ComplexFloat::log10(_1_0i), _0_0i));
assert!(closef(ComplexFloat::log10(1.), 0.));
}
#[test]
fn test_conj() {
assert_eq!(ComplexFloat::conj(_0_1i), Complex::new(0., -1.));
assert_eq!(ComplexFloat::conj(1.), 1.);
}
#[test]
fn test_is_nan() {
assert!(!ComplexFloat::is_nan(_1_0i));
assert!(!ComplexFloat::is_nan(1.));
assert!(ComplexFloat::is_nan(Complex::new(f64::NAN, f64::NAN)));
assert!(ComplexFloat::is_nan(f64::NAN));
}
#[test]
fn test_is_infinite() {
assert!(!ComplexFloat::is_infinite(_1_0i));
assert!(!ComplexFloat::is_infinite(1.));
assert!(ComplexFloat::is_infinite(Complex::new(
f64::INFINITY,
f64::INFINITY
)));
assert!(ComplexFloat::is_infinite(f64::INFINITY));
}
#[test]
fn test_is_finite() {
assert!(ComplexFloat::is_finite(_1_0i));
assert!(ComplexFloat::is_finite(1.));
assert!(!ComplexFloat::is_finite(Complex::new(
f64::INFINITY,
f64::INFINITY
)));
assert!(!ComplexFloat::is_finite(f64::INFINITY));
}
#[test]
fn test_is_normal() {
assert!(ComplexFloat::is_normal(_1_1i));
assert!(ComplexFloat::is_normal(1.));
assert!(!ComplexFloat::is_normal(Complex::new(
f64::INFINITY,
f64::INFINITY
)));
assert!(!ComplexFloat::is_normal(f64::INFINITY));
}
#[test]
fn test_arg() {
assert!(closef(
ComplexFloat::arg(_0_1i),
core::f64::consts::FRAC_PI_2
));
assert!(closef(ComplexFloat::arg(-1.), core::f64::consts::PI));
assert!(closef(ComplexFloat::arg(-0.), core::f64::consts::PI));
assert!(closef(ComplexFloat::arg(0.), 0.));
assert!(closef(ComplexFloat::arg(1.), 0.));
assert!(ComplexFloat::arg(f64::NAN).is_nan());
}
}

View File

@@ -0,0 +1,148 @@
//! Rand implementations for complex numbers
use crate::Complex;
use num_traits::Num;
use rand::distributions::Standard;
use rand::prelude::*;
impl<T> Distribution<Complex<T>> for Standard
where
T: Num + Clone,
Standard: Distribution<T>,
{
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Complex<T> {
Complex::new(self.sample(rng), self.sample(rng))
}
}
/// A generic random value distribution for complex numbers.
#[derive(Clone, Copy, Debug)]
pub struct ComplexDistribution<Re, Im = Re> {
re: Re,
im: Im,
}
impl<Re, Im> ComplexDistribution<Re, Im> {
/// Creates a complex distribution from independent
/// distributions of the real and imaginary parts.
pub fn new(re: Re, im: Im) -> Self {
ComplexDistribution { re, im }
}
}
impl<T, Re, Im> Distribution<Complex<T>> for ComplexDistribution<Re, Im>
where
T: Num + Clone,
Re: Distribution<T>,
Im: Distribution<T>,
{
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Complex<T> {
Complex::new(self.re.sample(rng), self.im.sample(rng))
}
}
#[cfg(test)]
fn test_rng() -> impl RngCore {
/// Simple `Rng` for testing without additional dependencies
struct XorShiftStar {
a: u64,
}
impl RngCore for XorShiftStar {
fn next_u32(&mut self) -> u32 {
self.next_u64() as u32
}
fn next_u64(&mut self) -> u64 {
// https://en.wikipedia.org/wiki/Xorshift#xorshift*
self.a ^= self.a >> 12;
self.a ^= self.a << 25;
self.a ^= self.a >> 27;
self.a.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
for chunk in dest.chunks_mut(8) {
let bytes = self.next_u64().to_le_bytes();
let slice = &bytes[..chunk.len()];
chunk.copy_from_slice(slice)
}
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> {
Ok(self.fill_bytes(dest))
}
}
XorShiftStar {
a: 0x0123_4567_89AB_CDEF,
}
}
#[test]
fn standard_f64() {
let mut rng = test_rng();
for _ in 0..100 {
let c: Complex<f64> = rng.gen();
assert!(c.re >= 0.0 && c.re < 1.0);
assert!(c.im >= 0.0 && c.im < 1.0);
}
}
#[test]
fn generic_standard_f64() {
let mut rng = test_rng();
let dist = ComplexDistribution::new(Standard, Standard);
for _ in 0..100 {
let c: Complex<f64> = rng.sample(&dist);
assert!(c.re >= 0.0 && c.re < 1.0);
assert!(c.im >= 0.0 && c.im < 1.0);
}
}
#[test]
fn generic_uniform_f64() {
use rand::distributions::Uniform;
let mut rng = test_rng();
let re = Uniform::new(-100.0, 0.0);
let im = Uniform::new(0.0, 100.0);
let dist = ComplexDistribution::new(re, im);
for _ in 0..100 {
// no type annotation required, since `Uniform` only produces one type.
let c = rng.sample(&dist);
assert!(c.re >= -100.0 && c.re < 0.0);
assert!(c.im >= 0.0 && c.im < 100.0);
}
}
#[test]
fn generic_mixed_f64() {
use rand::distributions::Uniform;
let mut rng = test_rng();
let re = Uniform::new(-100.0, 0.0);
let dist = ComplexDistribution::new(re, Standard);
for _ in 0..100 {
// no type annotation required, since `Uniform` only produces one type.
let c = rng.sample(&dist);
assert!(c.re >= -100.0 && c.re < 0.0);
assert!(c.im >= 0.0 && c.im < 1.0);
}
}
#[test]
fn generic_uniform_i32() {
use rand::distributions::Uniform;
let mut rng = test_rng();
let re = Uniform::new(-100, 0);
let im = Uniform::new(0, 100);
let dist = ComplexDistribution::new(re, im);
for _ in 0..100 {
// no type annotation required, since `Uniform` only produces one type.
let c = rng.sample(&dist);
assert!(c.re >= -100 && c.re < 0);
assert!(c.im >= 0 && c.im < 100);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,186 @@
use super::Complex;
use core::ops::Neg;
#[cfg(any(feature = "std", feature = "libm"))]
use num_traits::Float;
use num_traits::{Num, One, Pow};
macro_rules! pow_impl {
($U:ty, $S:ty) => {
impl<'a, T: Clone + Num> Pow<$U> for &'a Complex<T> {
type Output = Complex<T>;
#[inline]
fn pow(self, mut exp: $U) -> Self::Output {
if exp == 0 {
return Complex::one();
}
let mut base = self.clone();
while exp & 1 == 0 {
base = base.clone() * base;
exp >>= 1;
}
if exp == 1 {
return base;
}
let mut acc = base.clone();
while exp > 1 {
exp >>= 1;
base = base.clone() * base;
if exp & 1 == 1 {
acc = acc * base.clone();
}
}
acc
}
}
impl<'a, 'b, T: Clone + Num> Pow<&'b $U> for &'a Complex<T> {
type Output = Complex<T>;
#[inline]
fn pow(self, exp: &$U) -> Self::Output {
self.pow(*exp)
}
}
impl<'a, T: Clone + Num + Neg<Output = T>> Pow<$S> for &'a Complex<T> {
type Output = Complex<T>;
#[inline]
fn pow(self, exp: $S) -> Self::Output {
if exp < 0 {
Pow::pow(&self.inv(), exp.wrapping_neg() as $U)
} else {
Pow::pow(self, exp as $U)
}
}
}
impl<'a, 'b, T: Clone + Num + Neg<Output = T>> Pow<&'b $S> for &'a Complex<T> {
type Output = Complex<T>;
#[inline]
fn pow(self, exp: &$S) -> Self::Output {
self.pow(*exp)
}
}
};
}
pow_impl!(u8, i8);
pow_impl!(u16, i16);
pow_impl!(u32, i32);
pow_impl!(u64, i64);
pow_impl!(usize, isize);
pow_impl!(u128, i128);
// Note: we can't add `impl<T: Float> Pow<T> for Complex<T>` because new blanket impls are a
// breaking change. Someone could already have their own `F` and `impl Pow<F> for Complex<F>`
// which would conflict. We can't even do this in a new semantic version, because we have to
// gate it on the "std" feature, and features can't add breaking changes either.
macro_rules! powf_impl {
($F:ty) => {
#[cfg(any(feature = "std", feature = "libm"))]
impl<'a, T: Float> Pow<$F> for &'a Complex<T>
where
$F: Into<T>,
{
type Output = Complex<T>;
#[inline]
fn pow(self, exp: $F) -> Self::Output {
self.powf(exp.into())
}
}
#[cfg(any(feature = "std", feature = "libm"))]
impl<'a, 'b, T: Float> Pow<&'b $F> for &'a Complex<T>
where
$F: Into<T>,
{
type Output = Complex<T>;
#[inline]
fn pow(self, &exp: &$F) -> Self::Output {
self.powf(exp.into())
}
}
#[cfg(any(feature = "std", feature = "libm"))]
impl<T: Float> Pow<$F> for Complex<T>
where
$F: Into<T>,
{
type Output = Complex<T>;
#[inline]
fn pow(self, exp: $F) -> Self::Output {
self.powf(exp.into())
}
}
#[cfg(any(feature = "std", feature = "libm"))]
impl<'b, T: Float> Pow<&'b $F> for Complex<T>
where
$F: Into<T>,
{
type Output = Complex<T>;
#[inline]
fn pow(self, &exp: &$F) -> Self::Output {
self.powf(exp.into())
}
}
};
}
powf_impl!(f32);
powf_impl!(f64);
// These blanket impls are OK, because both the target type and the trait parameter would be
// foreign to anyone else trying to implement something that would overlap, raising E0117.
#[cfg(any(feature = "std", feature = "libm"))]
impl<'a, T: Float> Pow<Complex<T>> for &'a Complex<T> {
type Output = Complex<T>;
#[inline]
fn pow(self, exp: Complex<T>) -> Self::Output {
self.powc(exp)
}
}
#[cfg(any(feature = "std", feature = "libm"))]
impl<'a, 'b, T: Float> Pow<&'b Complex<T>> for &'a Complex<T> {
type Output = Complex<T>;
#[inline]
fn pow(self, &exp: &'b Complex<T>) -> Self::Output {
self.powc(exp)
}
}
#[cfg(any(feature = "std", feature = "libm"))]
impl<T: Float> Pow<Complex<T>> for Complex<T> {
type Output = Complex<T>;
#[inline]
fn pow(self, exp: Complex<T>) -> Self::Output {
self.powc(exp)
}
}
#[cfg(any(feature = "std", feature = "libm"))]
impl<'b, T: Float> Pow<&'b Complex<T>> for Complex<T> {
type Output = Complex<T>;
#[inline]
fn pow(self, &exp: &'b Complex<T>) -> Self::Output {
self.powc(exp)
}
}