7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rustの浮動小数点数テスト

7
Posted at

rustでテスト書いている時、f64やf32の数値の一致を確認したいことはありませんか。
浮動小数点数には誤差があり、計算を行っていくうちに誤差が累積していくことから、
厳密なイコールではなく、だいたい等しい事を確認したいことが多いかと思います。

そこで、だいたい等しい事を確認するためのクレートnearly_eqを作成しました。
(nearly equalではなくて正しくはapproximately equalだというツッコミはやめてください。作ってから気づきました。)

使い方

基本的な使い方は次の通り。

assert_nearly_eq!(チェックしたい値, チェックする値);
または
assert_nearly_eq!(チェックしたい値, チェックする値, 誤差);

誤差を入力しなかった場合、f32では1e-6、f64では1e-11、整数では0がデフォルトとなります。

実際は次の様になります。

# [macro_use]
extern crate nearly_eq;

fn main() {
    assert_nearly_eq!(1f64, 1.5f64, 0.6f64); // does not panic
    assert_nearly_eq!(0f64, 1e-12f64); // does not panic

    assert_nearly_eq!(1f64, 2f64); // panics
}

こんな風に配列のチェックも可能です。

# [macro_use]
extern crate nearly_eq;

fn main() {
    let left = vec![1f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
    let right = vec![1f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
    assert_nearly_eq!(left, right);
}

num-complex featureを有効にすると、複素数のチェックも可能

# [macro_use]
extern crate nearly_eq;
extern crate num_complex;

use num_complex::Complex;

fn main() {
    let left = Complex::new(1.0f64, 0.0);
    let right = Complex::new(1.0f64, 1e-12);
    assert_nearly_eq!(left, right);
}

当然組み合わせても問題ありません。

# [macro_use]
extern crate nearly_eq;
extern crate num_complex;

use num_complex::Complex;

fn main() {
    let left = vec![Complex::new(1.0f64, 0.0), Complex::new(2.0, 0.0)];
    let right = vec![Complex::new(1.0f64, 1e-12), Complex::new(2.0, 1e-12)];
    assert_nearly_eq!(left, right);
}

その他、ndarray等にも対応しております。

NearlyEqクレートを実装することにより、どのような引数でも対応できるようになります。

最後に

issue/PR募集中です。

7
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?