データベースで小数の繰り返しを表現する良い方法は何ですか?
例2.818181
、81
繰り返し
アイデア1
2.818181
非反復部分と反復部分に分けてからnon_repeat = 2.0
、repeat = .007
class Decimal < ActiveRecord::Base
attr_accessible :non_repeat, :repeat #floats
def to_f
to_s.to_f
end
def to_s
"#{non_repeat + repeat}#{repeat.to_s.gsub(/0\./, '') * 3}" #approximation
end
def self.random_new
a = rand(100)
b = rand(100) / 100.0
self.new(non_repeat: a, repeat: b)
end
end
アイデア2
分数を使用します。つまり、 に変わり2.818181
、 2 つの整数を31/11
保存して、31
11
class Decimal < ActiveRecord::Base
attr_accessible :numerator, :denominator #integers
def to_f
numerator / denominator
end
def to_s
to_f.to_s
end
def self.random_new
a = rand(100)
b = random_prime(...) # like 7, 9, 11
self.new(numerator: a, denominator: b)
end
end
繰り返し小数をランダムに生成する目的で、どのアイデアが優れていますか? それとも別の方法がありますか?