Giter Club home page Giter Club logo

approx's Introduction

approx

Build Status Version Documentation Downloads License

Approximate floating point equality comparisons and assertions for the Rust Programming Language.

approx's People

Contributors

adrianwong avatar brendanzab avatar brightly-salty avatar dependabot-preview[bot] avatar dushistov avatar efanzh avatar harrysarson avatar hmeyer avatar ilya-bobyr avatar jturner314 avatar mikedilger avatar paholg avatar qnighy avatar sebcrozet avatar superfluffy avatar torokati44 avatar vks avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

approx's Issues

Not working at all?

This is passing in my tests, am I using this wrong?

    ulps_eq!(12.3, 24.5);
    abs_diff_eq!(12.3, 24.5);

Maintenance status

This crate is very widely used; is there any report on it's maintenance status? There are several good PRs open to remove unsafe and fix some clippy warnings; I think it would be a good idea to review and merge those in and release a new version. (This library came up while using cargo-geiger on several different libraries.)

Absolute tolerance

I find this library really useful, however sometimes you actually want to compare two numbers using their absolute difference. Could it perhaps be desirable to have an additional macro for this purpose? I find this perhaps particularly useful when comparing with zero.

// The name is perhaps not perfect
assert_absdiff_eq!(x, y, tol = 1e-8);

// I actually suggest not providing a default tolerance, as I believe
// absolute difference should only be used when you already have
// a specific tolerance in mind

I could certainly try to make a PR for this, but I thought I'd see if there's interest in it first.

Release another version

Hiya, thanks for the great crate 🙇!

Please could another version be released?
Came across a case where the functionality in #48 is needed (hint: Amethyst 💎)

Thank you

`impl RelativeEq for Option<T: RelativeEq>`?

I'd like to be able to write the following code:

pub fn maybe_f32(foo: f32) -> Option<f32> {
    // ...
}

/// in test
let c = maybe_f32();
assert_relative_eq!(maybe_f32(123.0), None);

I could do:

assert!(maybe_f32().is_none());

However, the advantage with the first version, is that on failure I can also see the actual value that was returned from maybe_f32, speeding up debugging a little bit.

less than or equal to

This line:

ulps_eq.rs:61

                $U::abs(int_self - int_other) < max_ulps as $U

uses strictly less than. However I'd like to make the argument for using <=, and also point out that it will change the behavior and should come with a version bump.

In the randomascii article, he uses <= exclusively throughout. He comments about it in the comments below the article: https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/#li-comment-8342

Also, the similar lines of logic elsewhere in the crate use <= such as abs_diff_eq.rs and relative_eq using <= epsilon

If you use <, then anyone trying to do a comparison with max_ulps=0 and thinking this means the numbers must be exactly equal, would be suprised to see two exactly equal numbers coming out as not equal (because no absolute value is less than zero). At the interface of the crate, however, this doesn't happen because the epsilon based comparsion kicks in and overrides.

Automatically deriving implementations

Is there any outlook on automatic derivations of the traits in this crate?

I tried to write a derive crate, but got stuck. Deriving for example AbsDiffEq for structs could be done by calling AbsDiffEq::abs_diff_eq on all fields, in combination with an impl<T: Eq> AbsDiffEq for T. This last trait implementation collides however with the existing derivation implementations such as impl<'a, T: AbsDiffEq> AbsDiffEq for &'a T. I don't know how to solve this problem without removing these trait derivations, or until this work is finished.

Use macro on Rust 1.30

I replaced all #[macro_use] extern crate approx; in my project with simple use.

It went well for relative_eq!, but not for assert_relative_eq!. When I try to use it, the compiler tells me that __assert_approx is missing, then relative_eq is missing, so I need to type:

use approx::{assert_relative_eq, __assert_approx, relative_eq};

I know I can a) keep #[macro_use] or b) use approx::*; but neither are interesting.

Compilation with no_std fails.

Enabling the no_std feature does not compile because of the use of an unstable library feature:

error[E0658]: use of unstable library feature 'float_internals': internal routines only exposed for testing
 --> src/abs_diff_eq.rs:7:5
  |
7 | use core::num::Float;
  |     ^^^^^^^^^^^^^^^^
  |
  = help: add #![feature(float_internals)] to the crate attributes to enable

error[E0658]: use of unstable library feature 'float_internals': internal routines only exposed for testing
 --> src/relative_eq.rs:7:5
  |
7 | use core::num::Float;
  |     ^^^^^^^^^^^^^^^^
  |
  = help: add #![feature(float_internals)] to the crate attributes to enable

error[E0658]: use of unstable library feature 'float_internals': internal routines only exposed for testing
 --> src/ulps_eq.rs:5:5
  |
5 | use core::num::Float;
  |     ^^^^^^^^^^^^^^^^
  |
  = help: add #![feature(float_internals)] to the crate attributes to enable

Instead, I suggest:

  • Depending on num-traits in order to use their FloatCore trait instead of core::num::Float.
  • Making the activation of #![no_std] more idiomatic. Usually, we define a std feature that is enabled by default on the Cargo.toml. To activate the #![no_std] attribute, one has to depend on approx with no_default_features.

Improve Documentation

The documentation currently is not very clear as to how it computes things, and one reason I think is that nearly all the example just compare whether 1.0 is approximately equal to 1.0 which isn't very illustrative.

It would be good if there were examples at the crate level showing the differences between the various macros that illustrate when one should use abs_diff_eq! vs relative_eq! vs ulps_eq!. Additionally, the documentation for each macro is quite lacking (e.g. assert_relative_eq and relative_eq are not very helpful).

It is also unclear from the documentation what keyword arguments are allowed in which macros. Are the crate-level examples exhaustive ? Or can I also use max_relative in the ulps_eq! macro? Does the order matter? Because the examples show both:

relative_eq!(1.0, 1.0, epsilon = f64::EPSILON, max_relative = 1.0);
relative_eq!(1.0, 1.0, max_relative = 1.0, epsilon = f64::EPSILON);

What if I want to assert that two results should have "x decimal digits in common", is this possible?

Release a 1.0 version

This library appears to be the de-facto standard for approximate comparisons. Downstreams include ndarray and nalgebra. I just ran into an issue where ndarray is using an older version tied to an older version of num-complex. If you aren't planning on making breaking changes then it would be nice if you could bump to a 1.0 version so that feature additions don't require upstreams to bump their versions.

Transferral of repository

Seeing as this repository seems to be getting some love now (thank you to @sebcrozet in particular!!), I'm wondering if it would be a good idea to transfer it to a more appropriate org? I don't really have the time or energy to maintain it myself, but I feel bad stealing the clout.

`assert_relative_eq!()` fails in compilation

assert_relative_eq!(
   0.55,
   0.56
);

Compiles on version 0.4.0, but fails on 0.5.x

I don't think this is desired behavior, also I can not see another possible signature. And a bit more of docs for each macro would be awesome.

Please tag releases

Hey, I think it'd be great if you could tag a release in git when you publish to crates.io as this easily allows me to see what code went into a release and I can also see the changes.

clippy::if_then_panic warning (nightly)

This is not a pressing issue yet, but it appears in a nightly version of clippy, so you might be interested in addressing the lint ahead of time.

I'm using this simple snippet:

use approx::assert_relative_eq;

fn main() {
    assert_relative_eq!(1.0, 2.0);
}

When running cargo +nightly clippy, I get:

warning: only a `panic!` in `if`-then statement
 --> src\main.rs:4:2
  |
4 |     assert_relative_eq!(1.0, 2.0);
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(clippy::if_then_panic)]` on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#if_then_panic
  = note: this warning originates in the macro `__assert_approx` (in Nightly builds, run with -Z macro-backtrace for more info)

This occurred in the CI of the downstream project godot-rust, which treats clippy warnings as errors (the nightly workflow still passes though).


It has to do with how the __assert_approx macro is implemented.
Basically, the lint tries to detect the structure

if !cond { panic!(msg); }

and transform it into

assert!(cond, msg);

This would be one option to fix it, another would be to #[allow(clippy::if_then_panic)] the relevant statements.

I'm using rustc 1.57.0-nightly (5b210643e 2021-10-11).

V0.2 ist incompatible with nalgebra

Version 0.2 of approx is not compatible with nalgebra anymore:

130 |         relative_eq!(self.pos, other.pos)
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `approx::RelativeEq` is not implemented for `nalgebra::Point<f32, nalgebra::U3>`

Add debug versions of assert_relative_eq! and friends

It would be great to have debug_assert_{relative|ne}_{eq|ne} macros that are only checked in non optimized builds, similar to debug_assert! from the standard library.

Implementation should be straightforward, something like:

macro_rules! debug_assert_relative_eq {
    ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_relative_eq!($($arg)*); })
}

relative_eq() has incorrect behavior for small values

Consider this small example:

let diff: f32 = 1.0e-7;
let x: f32 = 1.0e-5;
let y = x - diff;
assert_ne!(x, y);
relative_eq!(x, y) // returns true, but should be false

Note that x and y are normal, full-precision floating-point values (not "subnormals"), above the epsilon threshold, and their relative error is (x - y)/x, which equals 0.01, far above the default threshold. However, they are marked as "relatively equal" in the current implementation.

The problem is in the logic of the provided implementation of RelativeEq::relative_eq() for f32 and f64, namely these lines:

let abs_diff = $T::abs(self - other);
// For when the numbers are really close together
if abs_diff <= epsilon {
return true;
}

While the precise definition of relative equality and the parameters epsilon and max_relative are never clearly specified in the documentation, based on the referenced blog posts, it seems that the intention is to use epsilon as a zero-closeness threshold, and max_relative as the relative error threshold.

The issue stems from not checking the two input numbers (self and other in this case) individually against epsilon for a zero-threshold, but instead testing their absolute difference against epsilon. As a result, relative equality works as expected for large numbers, but in practice defaults to absolute-difference equality for values less than 1.

Support for slices?

In data science use cases, the most frequent test is to assert approximate equality of entire float data vectors. For instance in Numpy based code, testing with assert_allclose is ubiquitous. I'm looking for the equivalent in Rust.

As far as I can see, the macros currently doesn't support slices. Is there an interest to support them?

Issue when using num_complex with assert_relative_eq

Hi,

My formal gist is working really well. Unfortunately, we have made some change in our dependencies and now we don't use the crate num anymore, but we rely on num_complex. Here is the gist to reproduce my error.

I have used the save num-complex version as your library but I face this error when I do a cargo build:

error[E0277]: the trait bound `num_complex::Complex<{float}>: approx::RelativeEq` is not satisfied      
  --> src/main.rs:28:5
   |
28 |     assert_relative_eq!(Complex::new(0.2, 0.1), Complex::new(0.2, 0.1));
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `approx::RelativeEq` is not implemented for `num_complex::Complex<{float}>`
   |
   = note: required by `approx::Relative`
   = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

error[E0277]: the trait bound `num_complex::Complex<{float}>: approx::RelativeEq` is not satisfied
  --> src/main.rs:28:5
   |
28 |     assert_relative_eq!(Complex::new(0.2, 0.1), Complex::new(0.2, 0.1));
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `approx::RelativeEq` is not implemented for `num_complex::Complex<{float}>`
   |
   = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

error[E0277]: the trait bound `num_complex::Complex<f64>: approx::RelativeEq` is not satisfied
  --> src/main.rs:29:5
   |
29 |     assert_relative_eq!(sh.as_slice().unwrap(), gt.as_slice().unwrap());
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `approx::RelativeEq` is not implemented for `num_complex::Complex<f64>`
   |
   = note: required because of the requirements on the impl of `approx::RelativeEq` for `[num_complex::Complex<f64>]`
   = note: required because of the requirements on the impl of `approx::RelativeEq` for `&[num_complex::Complex<f64>]`
   = note: required by `approx::Relative`
   = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

error: aborting due to 3 previous errors

I have checked and you use the num-complex type so I don't get why it's not working. Did I miss something?

[Question] Using a slice of Complex type.

Hi,
I see that you have implemented assert_relative_eq! for complex and slices. But somehow, I cannot do a assert_relative_eq! on a slice of Complex and I can't find out what is wrong with my code?
This is the output of cargo run:

  --> src/main.rs:29:5
   |
29 |     assert_relative_eq!(&sh.as_slice().unwrap(), &gt.as_slice().unwrap());
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `[num::Complex<{float}>]` does not have a constant size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `[num::Complex<{float}>]`
   = note: required because of the requirements on the impl of `approx::AbsDiffEq` for `&[num::Complex<{float}>]`
   = note: required because it appears within the type `approx::Relative<&&[num::Complex<{float}>]>`
   = note: required by `std::default::Default::default`
   = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

Here is a gist to reproduce what I'm trying to do.

Thanks for the help.

Give acceptable range on assertion failure

Currently, the output is indistinguishable from assert_eq!'s:

thread 'bsf::tests::score_examples' panicked at 'assert_ulps_eq!(scores[0], 590.0798357956826, max_ulps = 1)

    left  = 590.0798357956824
    right = 590.0798357956826

', src/bsf.rs:354:9

It would be nicer to give allowable ranges for both left/right based on the variance allowed.

Relicense under dual MIT/Apache-2.0

This issue was automatically generated. Feel free to close without ceremony if
you do not agree with re-licensing or if it is not possible for other reasons.
Respond to @cmr with any questions or concerns, or pop over to
#rust-offtopic on IRC to discuss.

You're receiving this because someone (perhaps the project maintainer)
published a crates.io package with the license as "MIT" xor "Apache-2.0" and
the repository field pointing here.

TL;DR the Rust ecosystem is largely Apache-2.0. Being available under that
license is good for interoperation. The MIT license as an add-on can be nice
for GPLv2 projects to use your code.

Why?

The MIT license requires reproducing countless copies of the same copyright
header with different names in the copyright field, for every MIT library in
use. The Apache license does not have this drawback. However, this is not the
primary motivation for me creating these issues. The Apache license also has
protections from patent trolls and an explicit contribution licensing clause.
However, the Apache license is incompatible with GPLv2. This is why Rust is
dual-licensed as MIT/Apache (the "primary" license being Apache, MIT only for
GPLv2 compat), and doing so would be wise for this project. This also makes
this crate suitable for inclusion and unrestricted sharing in the Rust
standard distribution and other projects using dual MIT/Apache, such as my
personal ulterior motive, the Robigalia project.

Some ask, "Does this really apply to binary redistributions? Does MIT really
require reproducing the whole thing?" I'm not a lawyer, and I can't give legal
advice, but some Google Android apps include open source attributions using
this interpretation. Others also agree with
it
.
But, again, the copyright notice redistribution is not the primary motivation
for the dual-licensing. It's stronger protections to licensees and better
interoperation with the wider Rust ecosystem.

How?

To do this, get explicit approval from each contributor of copyrightable work
(as not all contributions qualify for copyright, due to not being a "creative
work", e.g. a typo fix) and then add the following to your README:

## License

Licensed under either of

 * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
 * MIT license ([LICENSE-MIT](LICENSE-MIT) or 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.

and in your license headers, if you have them, use the following boilerplate
(based on that used in Rust):

// Copyright 2016 approx Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

It's commonly asked whether license headers are required. I'm not comfortable
making an official recommendation either way, but the Apache license
recommends it in their appendix on how to use the license.

Be sure to add the relevant LICENSE-{MIT,APACHE} files. You can copy these
from the Rust repo for a plain-text
version.

And don't forget to update the license metadata in your Cargo.toml to:

license = "MIT OR Apache-2.0"

I'll be going through projects which agree to be relicensed and have approval
by the necessary contributors and doing this changes, so feel free to leave
the heavy lifting to me!

Contributor checkoff

To agree to relicensing, comment with :

I license past and future contributions under the dual MIT/Apache-2.0 license, allowing licensees to chose either at their option.

Or, if you're a contributor, you can check the box in this repo next to your
name. My scripts will pick this exact phrase up and check your checkbox, but
I'll come through and manually review this issue later as well.

Inconsistent temporary value behavior with `assert_eq!`

For example, in this code:

fn foo(x: &[f64]) {
    assert_eq!(vec![0.0].as_slice(), x); // OK.
    approx::assert_relative_eq!(vec![0.0].as_slice(), x); // Error.
}

assert_eq! works fine, but approx::assert_relative_eq reports “temporary value dropped while borrowed” error.

Unecessary std feature

A quick grep through the approx crate seems to show that there is no need to have a std feature. Notably, approx could support no_std by default without any adverse effects downstream. It may make sense to remove the std feature altogether and only use core inside approx. The std feature could be left as a vestigial artifact that does nothing (and does not even control whether no_std is or is not present). In the next breaking release std feature can be removed.

Any thoughts? If this sounds good it should be pretty simple to remove the feature.

Adding messages to assert_* macros

It would be great to extend the assert_* macros to accept a custom panic message, the way assert_eq! does:

assert_eq!(a, b, "Failed to compare a and b; a={}, b={}", a, b);

Changelog for version updates would be nice

As an engineer with a project that depends on this crate
When dependa-bot creates a PR to update to the latest version
I should be able to find a Changelog that indicates what has changed between versions
So I can be sure the update will not break any functionality the app is using.

assert_abs_diff_eq does not allow specifying epsilon

Why can't I specify custom epsilon with assert_abs_diff_eq but I can with abs_diff_eq

// not possible
assert_abs_diff_eq!(1.0, 1.0, epsilon = f64::EPSILON);

// possible
abs_diff_eq!(1.0, 1.0, epsilon = f64::EPSILON);

This makes me unable to write write Rust tests so that I can see the left and right values on test errors when setting epsilon is needed.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.