LoginSignup
0
0

More than 1 year has passed since last update.

【Ruby on Rails】浮動小数点の計算誤差を解消する方法

Posted at

前提条件

  • Ruby 3.1.0
  • Rails 7.0.4

事象

浮動小数点の計算を実装すると、下記のように計算結果に誤差が発生してしまう。

> 1 - 0.8
=> 0.19999999999999996

方法

Rational(有理数)クラスを使う

浮動小数点の値にrationalizeをつけることで、有理数とすることができる。有理数に直した上で計算し、再びfloat型に戻せば誤差が発生することなく計算することができる。

num = 1 - 0.8.rationalize
num = num.to_f

参考

0
0
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
0
0