4
3

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.

Haskellで有理数の計算をするときはData.Ratioを使う

Last updated at Posted at 2014-12-31

Haskellで誤差なく有理数を扱いたかったら Data.Ratio を使いましょうってだけです。久々に触ったら完全に忘れてたのでメモ。

%演算子でIntegral2個からその比を作れます。通常は整数の比を取って有理数として使うことになるでしょう。

import Data.Ratio
x = 1 % 3
y = 2 % 6 -- 内部的に通分してくれる
x == y -- True

この有理数から分子(numerator)と分母(denominator)を取り出すこともできます。

import Data.Ratio
xs = map (% 2) [1..9] -- [1/2,1,3/2,2...9/2]というリスト
ys = filter ((1 ==) . denominator) xs -- xsから整数(分母が1のもの)だけ抜き出したリスト
4
3
0

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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?